将回车添加到字符串

时间:2012-04-10 20:38:06

标签: c# linq

我有一个很长的字符串。

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'";

我想要

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

换句话说。也许它喜欢:

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

我需要一个简洁的代码。也许是LINQ。感谢。

7 个答案:

答案 0 :(得分:40)

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

另外,从性能角度来看,这里是我见过的三种当前解决方案如何叠加超过100k次迭代:

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 ReplaceWithConstant 在彼此的误差范围内,因此在功能上没有区别。

使用Environment.NewLine优先于"\n",以提高可读性和一致性,类似于使用String.Empty代替""

答案 1 :(得分:25)

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

答案 2 :(得分:0)

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

答案 3 :(得分:0)

另一种选择:

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

答案 4 :(得分:0)

环境。应该使用NewLine作为Dan Rigby说,但String.Empty存在一个问题。无论是在读取之前还是之后读取,它都将始终为空。我昨天在项目中遇到了问题。我删除它,它按照预期的方式工作。最好声明变量,然后在需要时调用它。 String.Empty将始终保持为空,除非需要初始化变量,然后才应使用String.Empty。我以为我会为每个人抛出这个tid-bit,因为我已经体验过它。

答案 5 :(得分:0)

我建议使用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);

{{1}}

答案 6 :(得分:-2)

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