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


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!
 
Ad

Advertisements

M

Miha Markic

Hi,

I would reverse the logic by adding newline beforhand:
textBox1.Text+= (textBox1.Text.Length>0 ? "\r\n": string.Empty) + line;
 
J

Jon Skeet [C# MVP]

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.
 
Ad

Advertisements


Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top