我有一个长字符串。
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'+.....;
我需要一个简洁的代码。也许林克。谢谢。
最佳答案
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);
拆分连接:
string s2 = String.Join("," + Environment.NewLine, s1.Split(','));
ReplaceWithEnvironmentNewLine 和 ReplaceWithConstant 在彼此的误差范围内,因此在功能上没有区别。
为了可读性和一致性,使用 Environment.NewLine
应该优于 "\n"
,类似于使用 String.Empty
而不是“”
。
关于c# - 向字符串添加回车符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10096100/