rj487
rj487

Reputation: 4634

Encounter format trouble in concatenating String

The file format is look like

abc def 
    ghy jk
          lmp

And here is my code

StreamReader file = new StreamReader("./test.txt");
string afterreplace = "";
while ((line = file.ReadLine()) != null)
{
    Console.WriteLine(line);
    afterreplace = String.Concat(afterreplace, line); 
}
Console.WriteLine(afterreplace);

However I got this in my output

It doesn't match the original file

abc def     ghy jk      lmp

Of cause I can add some newline character, I really want to know why it cause

Does String.Concat() ignore the \n? How could I achieve my expectation?

Upvotes: 0

Views: 37

Answers (1)

user743382
user743382

Reputation:

It's not string.Concat that's doing that, it's file.ReadLine(). But you don't notice that in your output directly, because Console.WriteLine adds an extra newline.

From StreamReader.ReadLine (emphasis mine):

Remarks

A line is defined as a sequence of characters followed by a line feed ("\n"), a carriage return ("\r"), or a carriage return immediately followed by a line feed ("\r\n"). The string that is returned does not contain the terminating carriage return or line feed. [...]

Upvotes: 1

Related Questions