Home > Blockchain >  How to add a line break after the last occurence of a space in C#?
How to add a line break after the last occurence of a space in C#?

Time:06-09

I have the following function:

public void GetTextTab(string txt, int tab)
{
    txtlist.Clear();
    int textparagraph = txt.Length;
    string str;
    int indexer = 0;
    int counter;
    if (tab == 3)
    {
        charcounter = 50;

    }
    else
    {
        charcounter = 60;

    }
    for (int i = 0; i < (txt.Length / charcounter)   1; i  )
    {

        counter = textparagraph - indexer;
        if (counter < charcounter)
        {
            str = txt.Substring(indexer, counter);
            indexer = indexer   charcounter;
            str = str.Trim();
            txtlist.Add(str);
            return;
        }

        str = txt.Substring(indexer, charcounter);

        if ((charcounter == 50) && (str.LastIndexOf(" ") != 49) || (charcounter == 60) && (str.LastIndexOf(" ") != 59))
        { 
            charcounter = str.LastIndexOf(" ");
        }

        str = txt.Substring(indexer, charcounter);

        str = str.Trim();

        indexer = indexer   charcounter;
        txtlist.Add(str);
    }

}

What it does is reading text paragraphs and creating separate rows from them with 50 or 60 characters in a Word file. What I want to do do is a line break in each line after the last occurence of a space (" ") so that the text goes to a new row and the words don't get divided.

This is my input:

Aaczqwfasda dsafewrgfdhgf klgfdlffwerqwepqcz dsadsaewqdasdas

What I get is something like this:

Aaczqwfasda dsafewrgfdhgf klgfdlff
werqwepqcz dsadsaewqdasdas

What I need is that:

Aaczqwfasda dsafewrgfdhgf
klgfdlffwerqwepqcz dsadsaewqdasdas

I tried doing this by writing the last if-statement at the end of the code but it's still not working properly - it only does for the first row. For the next ones the words keep getting divided.

What can I do to achieve what I want? Any help would be greatly appreciated.

CodePudding user response:

Here is how you can use the IndexOf to determine spot that you need to split the string at 60 characters

string s = "Aaczqwfasda dsafewrgfdhgf klgfdlffwerqwepqcz dsadsaewqdasdas";
int iCounter = 0;
while(true)
{
    int temp = s.IndexOf(' ', iCounter   1);
    if (temp > 0 && temp < 61)
        iCounter = temp;
    //break if we have no more spaces or exceed the 60 char limit
    if (temp == -1 || temp > 60) break;
}

MessageBox.Show(s.Substring(0,iCounter));
  • Related