[c#] Add carriage return to a string

I have a long string.

string s1 = "'99024','99050','99070','99143','99173','99191','99201','99202','99203','99204','99211','99212','99213','99214','99215','99217','99218','99219','99221','99222','99231','99232','99238','99239','99356','99357','99371','99374','99381','99382','99383','99384','99385','99386','99391','99392'";

I want

string s2 = 
            "'99024',
             '99050',
             '99070',
             '99143',
             '99173',
             '99191',
             '99201',
             '99202',....";

In other words. Maybe it likes:

string s2 = "'99024',"+'\n'+"'99050',"+'\n'+"'99070',"+'\n'+"'99143',"+'\n'+.....;

I need a concise code. Maybe LINQ. Thanks.

This question is related to c# linq

The answer is


string s2 = s1.Replace(",", ",\n") + ",....";

string s2 = s1.Replace(",", "," + Environment.NewLine);

Also, just from a performance perspective, here's how the three current solutions I've seen stack up over 100k iterations:

ReplaceWithConstant           - Ms: 328, Ticks: 810908
ReplaceWithEnvironmentNewLine - Ms: 310, Ticks: 766955 
SplitJoin                     - Ms: 483, Ticks: 1192545

ReplaceWithConstant:

string s2 = s1.Replace(",", ",\n");

ReplaceWithEnvironmentNewLine:

string s2 = s1.Replace(",", "," + Environment.NewLine);

SplitJoin:

string s2 = String.Join("," + Environment.NewLine, s1.Split(','));

ReplaceWithEnvironmentNewLine and ReplaceWithConstant are within the margin of error of each other, so there's functionally no difference.

Using Environment.NewLine should be preferred over "\n" for the sake readability and consistency similar to using String.Empty instead of "".


string s2 = s1.Replace(",", ",\r\n");


Environment.NewLine should be used as Dan Rigby said but there is one problem with the String.Empty. It will remain always empty no matter if it is read before or after it reads. I had a problem in my project yesterday with that. I removed it and it worked the way it was supposed to. It's better to declare the variable and then call it when it's needed. String.Empty will always keep it empty unless the variable needs to be initialized which only then should you use String.Empty. Thought I would throw this tid-bit out for everyone as I've experienced it.


I propose use StringBuilder

string s1 = "'99024','99050','99070','99143','99173','99191','99201','99202','99203','99204','99211','99212','99213','99214','99215','99217','99218','99219','99221','99222','99231','99232','99238','99239','99356','99357','99371','99374','99381','99382','99383','99384','99385','99386','99391','99392'";

var stringBuilder = new StringBuilder();           

foreach (var s in s1.Split(','))
{
    stringBuilder.Append(s).Append(",").AppendLine();
}
Console.WriteLine(stringBuilder);

Another option:

string s2 = String.Join("," + Environment.NewLine, s1.Split(','));