Ad

How To Split A String Into Multiple Lines If More Than 37 Characters Are Present

- 1 answer

how to split a string into multiple lines if more than 37 characters are present?

Example sentence

The Quick Brown Fox Jumped Over The Lazy Dog

It should make it

The Quick Brown Fox Jumped Over The
Lazy Dog

Although the 37th character is 'L'

I want to group by words.

Here is my code

private string sentence(string statement)
{
    string completedWord = "";
    string temp = "";
    string[] wordArray = statement.Split(' ');
    for (int i = 0; i < wordArray.Length; i++)
    {
        temp = completedWord + wordArray[i] + ' ';
        if (temp.Length < 37)
        {
            completedWord = completedWord + wordArray[i] + ' ';
        }
        else
        {
            completedWord = completedWord + "\n" + wordArray[i] + ' ';
        }
        temp = "";
    }
    return completedWord;
}

Once the sentence is 37 characters, it keeps doing else. I want each line to be 37 before adding \n. This only happens if the sentence is much longer than 37 characters

Ad

Answer

This should do the trick. I'll use the StringBuilder for convenience, by the way.

static string sentence(string statement)
{
  if (statement.Length > 37)
  {
    var words = statement.Split(' ');        
    StringBuilder completedWord = new StringBuilder();
    int charCount = 0;

    if (words.Length > 1)
    {
      for (int i = 1; i < words.Length - 1; i++)
      {
        charCount += words[i].Length;
        if (charCount >= 37)
        {
          completedWord.AppendLine();
          charCount = 0;
        }

        completedWord.Append(words[i]);
        completedWord.Append(" ");
      }
    }

    // add the last word
    if (completedWord.Length + words[words.Length - 1].Length >= 37)
    {
      completedWord.AppendLine();
    }
    completedWord.Append(words[words.Length - 1]);
    return completedWord.ToString();
  }
  return statement;
}
Ad
source: stackoverflow.com
Ad