ASP.NET Cafe
new tricks every week

ForceWrap or when you need a whitespace

Sunday, 8 June 2008 07:08 by dmitriy

Sometimes on websites with user content you can find some design issues because of their content. Actually, I'm about the stuff like

"Swimming*Skimboaring*AquaFitness*Snorkeling*Kayaking*Basketball*Archery*Volleyball*Soccer*Table Tennis*Mini Golf*Badminton*Rock Climbing* Kiteboarding*Fencing*Gymnastics*Yoga*Pilates*"

But we ( as developers want to get rid of such ugly stuff that moves across the bounds of area and can't be wrapped - because there are no white-space inside.

For this I just written force wrap function. It is quite simple, using regular expressions

[code=cs] 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;
        }[/code] 

 

First parameter - the string you want to output, the second - max lenght is chars. Return value is new string with whitespace inserted if needed.

I think this is useful, but if there are something better, please let me know. 

 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Categories:   ASP.NET | C#
Actions: E-mail | del.icio.us | Kick it! | DZone it! | Permalink | Comments (0) | Comment RSSRSS comment feed