Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add carriage return to a string

Tags:

c#

linq

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.


2 Answers

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

like image 151
Dan Rigby Avatar answered Sep 14 '25 06:09

Dan Rigby


string s2 = s1.Replace(",", ",\n");
like image 38
Servy Avatar answered Sep 14 '25 07:09

Servy