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)
   {
       do
       {
           if(sampleText[limitReached] == ' ')
           {
               sampleText= sampleText.Insert(limitReached, "n");
               limitReached += charsLimit + 2;
           }
           else
           {
               limitReached--;
           }
       } while ((sampleText.Length - limitReached) > charsLimit);
   }
   return sampleText;
}



No Comments


You can leave the first : )



Leave a Reply

Your email address will not be published. Required fields are marked *