Take away "\r\n" from end of String

  • Thread starter Thread starter Tomomichi Amano
  • Start date Start date
T

Tomomichi Amano

Hello!
I am making a program where it reads out a TXT file like this...

string line=sr.ReadLine();
textBox1.Text+=line += "\r\n";

The problem with this code is that, each time it loads a file, a unneeded
"\r\n" is added to the end of the text.

So, I would like know how to take away "\r\n" from the end of a string.

Thanks in advance!
 
Hi,

I would reverse the logic by adding newline beforhand:
textBox1.Text+= (textBox1.Text.Length>0 ? "\r\n": string.Empty) + line;
 
Tomomichi Amano said:
Hello!
I am making a program where it reads out a TXT file like this...

string line=sr.ReadLine();
textBox1.Text+=line += "\r\n";

That code looks relatively unreadable to me - why are you using +=
instead of just + on the second part? It's easier (IMO) to read:

textBox1.Test += line+"\r\n";
The problem with this code is that, each time it loads a file, a unneeded
"\r\n" is added to the end of the text.

So, I would like know how to take away "\r\n" from the end of a string.

Just take a substring which doesn't include the last two characters:

string x = x.Substring(0, x.Length-2);

However, the above will be very inefficient, particularly if the file
is long. It would be better to use a StringBuilder to build up the
whole string:

string line = sr.ReadLine();
stringBuilder.Append(line);
stringBuilder.Append("\r\n");

and *then* convert it to a string at the end.
 
Back
Top