65.9K
CodeProject is changing. Read more.
Home

Wrap a string to a given width

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1 vote)

Mar 1, 2010

CPOL
viewsIcon

4240

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.
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.