Search code examples
c#stringnewlineindexofsplice

C# Editing a string to add newlines at certain lengths


I'm building an application that needs to deal with twitter messages. I have need of a functionality that cuts a string up at 30 characters, if the character at the 30 index isn't a space it will count back till it finds a space and add a \n to it so that it displays as multi line in my application.

I've tried several approaches but my knowledge of C# isn't that amazing yet. I got something basic going.

string[] stringParts = new string[5];
string temp = jsonData["results"][i]["text"].ToString();
int length = 30;

for(int count = length-1; count >= 0; count--)
{
    if(temp[count].Equals(" "))
    {
        Debug.Log(temp[count]);
    } 
}

I figured i'd use Split and add the result to an array, but i can't seem to get it working.


Solution

  • A better approach may be to split by spaces and reconstruct for the array lines that are shorter than 30 characters.

    Here is an outline of how I would do this (untested):

    string[] words = myString.Split(' ');
    StringBuilder sb = new StringBuilder();
    int currLength = 0;
    foreach(string word in words)
    {
        if(currLength + word.Length + 1 < 30) // +1 accounts for adding a space
        {
          sb.AppendFormat(" {0}", word);
          currLength = (sb.Length % 30);
        }
        else
        {
          sb.AppendFormat("{0}{1}", Environment.NewLine, word);
          currLength = 0;
        }
    }