Search code examples
c#stringreplacetrim

Trimming empty lines resulting from splitting a string


I have a rich text box and have more than 100 lines of sentences. I am getting my sentences from reader[0] and using split for each data... finally adding ); for end of the each line. but when I check my sentences I see some lines end with ))): and some of them ends with )); so what I want to do is reduce.

My reader brings the sentence like below: and last sentence has some empty space but some how trim doesnt work to make last ) bring to right after the sentence like this sentence)

 my first (sentence(1))
 my second (sentence)
 my last (sentence

)

my code:

string[] splitted = reader[0].ToString().Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);

    foreach (string line in splitted)
    {
     RichTextBox1.AppendText(Environment.NewLine + line.Trim() + ");" + Environment.NewLine);

    if ((line.Trim().EndsWith(")));")) || (line.Trim().EndsWith("));")))
    {
     line.replace(");",";");
    }
 }

original:

my first (sentence(1)));
my second (sentence));
my last (sentence);

should be:

my first (sentence(1));
my second (sentence);
my last (sentence);

Solution

  • this could do the trick (if every "))" is wrong), you need to "fix" the strings before they are added to the textbox

     RichTextBox1.AppendText(Environment.NewLine + line.Trim().Replace("));",");") + ");" + Environment.NewLine);
    

    edit:

    you could try doing it with replaces alone

    first replace Environment.NewLine + " my" with "{line}my" then replace Environment.NewLine with "" then replace "{line}" with ";" + Environment.NewLine

    that should give you the result