Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Wrap a string to a given width

5.00/5 (1 vote)
1 Mar 2010CPOL 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)