Click here to Skip to main content
15,891,943 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

Wrap a string to a given width

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
1 Mar 2010CPOL 4.1K   1  
This piece of code is pretty fine but I have a confusion. I always used an old trick which utilizes a single 'for' loop and only splits the incoming string for array of words. After that you can apply your logic to store that in List. I think both logic will take approx same time but your logic...
This piece of code is pretty fine but I have a confusion. I always used an old trick which utilizes a single 'for' loop and only splits the incoming string for array of words. After that you can apply your logic to store that in List. I think both logic will take approx same time but your logic seems to be more complicated in terms of code. (I didn't get time to test your code in terms of time required).

If required one can add 'padding' stuff that you added wherever needed.


C#
public static List<String> DoWrapping(string sourceText, int maxLength)
        {
              // Do necessary null or empty checking
            //if (text.Length == 0) return null;
  
            string[] Words = sourceText.Split(' ');
            // For avoiding any confusion if required you can 
//also replace '\n', '\r' by ' ' before 
//splitting. Not suggested.

            List<string> lstLines = new List<string>();
            var considerLine = "";
  
            foreach (var word in Words)
            {
  
                if ((considerLine.Length > maxLength) ||
                    ((considerLine.Length + word.Length) > maxLength))
                 {
                     lstLines.Add(considerLine);
                     considerLine = "";
                 }
  
                if (considerLine.Length > 0)
                {
                     considerLine += " " + word;
                }
                else
                     considerLine += word;
  
            }
  
            if (considerLine.Length > 0)
                 lstLines.Add(considerLine);
  
            return lstLines;
        }


This logic will not alter any of the included word. Let me know your comments.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --