24

我有一长串。

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。谢谢。

4

7 回答 7

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

此外,仅从性能的角度来看,以下是我见过的三个当前解决方案如何叠加超过 100k 次迭代:

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

替换常量

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

ReplaceWithEnvironmentNewLine

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

拆分加入

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

ReplaceWithEnvironmentNewLineReplaceWithConstant在误差范围内,因此在功能上没有区别。

Environment.NewLine为了可读性和一致性,应该优先使用"\n"usingString.Empty而不是using ""

于 2012-04-10T20:40:24.523 回答
27
string s2 = s1.Replace(",", ",\n");
于 2012-04-10T20:39:26.573 回答
0
string s2 = s1.Replace(",", ",\n") + ",....";
于 2012-04-10T20:42:25.330 回答
0

另外一个选项:

string s2 = String.Join("," + Environment.NewLine, s1.Split(','));
于 2012-04-10T20:46:58.003 回答
0

Environment.NewLine 应该像 Dan Rigby 所说的那样使用,但是 String.Empty 存在一个问题。无论是在读取之前还是之后读取,它都将始终为空。昨天我的项目中有一个问题。我删除了它,它按预期的方式工作。最好先声明变量,然后在需要时调用它。String.Empty 将始终保持为空,除非需要初始化变量,然后才应该使用 String.Empty。我想我会把这个花絮扔给每个人,因为我经历过它。

于 2013-05-01T17:58:43.670 回答
0

我建议使用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);
于 2018-10-06T03:43:32.587 回答
-1

字符串 s2 = s1.Replace(",", ",\r\n");

于 2018-02-23T18:07:39.407 回答