Sometimes on websites with user content you can find some design issues because of post/comment/anything posted by user in case this is a long string without spaces.
For example “Swimming*Skimboaring*AquaFitness*Snorkeling*Kayaking*Basketball*Archery*Volleyball*Soccer*Table Tennis*Mini Golf*Badminton*Rock Climbing* Kiteboarding*Fencing*Gymnastics*Yoga*Pilates*”
This string without whitespace can’t be wrapped.
For cases like this I’ve just written force wrap function. It is quite simple, using regular expressions.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | protected static string ForceWrap(string aStr,int max) { Regex LongLine = new Regex(@"(?<long>\S{"+max.ToString()+",})"); MatchCollection matches = LongLine.Matches(aStr); // find all matches of "Long Strings" // if (matches.Count > 0) { StringBuilder sb = new StringBuilder(aStr); for (int i = 0; i < matches.Count; i++) { string s = matches[i].Groups["long"].Value; string origS = s; int segments = s.Length / max; for (int j = 1; j < (segments+1); j++) { int pos = j * max + (j-1); s = s.Insert( pos , " "); // Insert Space // } sb.Replace(origS, s); } aStr = sb.ToString(); } return aStr; } |
First parameter – the string you want to output, the second is max lenght is chars. Return value is new string with whitespace inserted if needed.
Hope this will help somebody.
