Friday, April 03, 2009

Breaking long running strings (line breaks)

I wrote this snip while ago for one of my oracle friends to break long running strings. Today I was in need of it again and I had to go through my library to find it. I am sure there is huge room for improvement. The job of the below code is to snip each paragraph using the max length into smaller strings.

public static string WrapText(string text, int maxLength)

{

// validate the incoming text

if (string.IsNullOrEmpty(text))

return text;



// break the string into smaller parts

string[] StringArray = System.Text.RegularExpressions.Regex.Split(

text,

"[\n]",

RegexOptions.Compiled RegexOptions.Multiline RegexOptions.Singleline RegexOptions.IgnoreCase);



// holds the string lines

List<string> StringLines = new List<string>();



// iterate through the array

foreach (string s in StringArray)

{

// the line is less then the allowed length

// add to the StringLines colleciton

if (s.Length <= maxLength)

StringLines.Add(s);

else

{

// longer string, so we use the start index to do our work

int StartIndex = 0;



// while loop breaking the long string

while (StartIndex <= s.Length)

{

// end index

int EndIndex = StartIndex + maxLength;



// trap for end index becoming longer than start index

if (EndIndex > s.Length)

{

// add to the StringLines colleciton

StringLines.Add(s.Substring(StartIndex, s.Length - StartIndex - 1));

break;

}

else

{

// character at end index position

string CharAtPosition = s[EndIndex].ToString();



// the character is not a space and not a (.) period

if (CharAtPosition != " " && CharAtPosition != ".")

{

// back track to find a space

// it is expected there will be a space at the end of a sentence

while (CharAtPosition != " " && EndIndex >= 0)

{

// trap in case it is a long word/url or something

if (EndIndex == 0)

break;



EndIndex = EndIndex - 1;

CharAtPosition = s[EndIndex].ToString();

}



// if end index becomes 0, then we need to take

// whatever is available

if (EndIndex == 0)

EndIndex = s.Length - 1;

}



// calculate the length we are going to take the snip and make the snip

int SubEndLenth = EndIndex - StartIndex;

StringLines.Add(s.Substring(StartIndex, SubEndLenth));



// increment the start index for the next request

StartIndex += SubEndLenth;



// if char at the position was a space, increment the start index by 1

// this is necessary becuase the next line will end up with a space as the starting charcter

if (CharAtPosition == " ") StartIndex += 1;

}

}

}

}

return string.Join("\r\n", StringLines.ToArray());

}

No comments: