Split string without breaking words

Let say we got a long string that need to be splitted in a series of rows (of a certain lenght) . If the length exceed, we need to go wrap the text on a new line ensuring words are not broken. The solution is quite simple after all, before going to the new line ensure you are in a white space:

public static string SplitStringWithDelimiter(int charsLimit, string sampleText)
   int limitReached = charsLimit;
   if(sampleText.Length > charsLimit)
           if(sampleText[limitReached] == ' ')
               sampleText= sampleText.Insert(limitReached, "\n");
               limitReached += charsLimit + 2;
       } while ((sampleText.Length - limitReached) > charsLimit);
   return sampleText;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s