C# Concat 多行字符串

C# Concat multiline string

我有两个字符串 A 和 B。

string A = @"Hello_
Hello_
Hello_";

string B = @"World
World
World";

我想将这两个字符串与函数调用相加,如下所示:

string AB = ConcatMultilineString(A, B)

函数应该return:

@"Hello_World
Hello_World
Hello_World"

对我来说,最好的方法是将字符串拆分成一个行数组,然后将所有行与“\r\n”相加,然后 returning 它。但这对我来说似乎是不好的做法,因为多行并不总是用“\r\n”表示。

有没有更可靠的方法?

Environment.NewLine 是使用“\r\n”的与平台无关的替代方法。

Environment.NewLine 可能有助于解决 "mulitple lines are not always indicated with "\r\n"" 问题

https://msdn.microsoft.com/de-de/library/system.environment.newline(v=vs.110).aspx

编辑:

如果您不知道多行是否分隔为 "\n""\r\n" 这可能会有所帮助:

input.Split(new string[] {"\n", "\r\n"}, StringSplitOptions.RemoveEmptyEntries);

删除空行。如果你不想这样使用: StringSplitOptions.None 代替。

另见此处:How to split strings on carriage return with C#?

单行解决方案:

var output = string.Join(System.Environment.NewLine, A.Split('\n')
                   .Zip(B.Split('\n'), (a,b) => string.Join("", a, b)));

我们在 \n 上拆分,因为无论是 \n\r 还是只是 \n,它都会包含 \n。剩下的 \r 似乎被忽略了,但是如果您觉得更安全,可以为 ab 添加对 Trim 的调用。

这是按照你的要求做的:

static string ConcatMultilineString(string a, string b)
{
    string splitOn = "\r\n|\r|\n";
    string[] p = Regex.Split(a, splitOn);
    string[] q = Regex.Split(b, splitOn);

    return string.Join("\r\n", p.Zip(q, (u, v) => u + v));
}

static void Main(string[] args)
{
    string A = "Hello_\rHello_\r\nHello_";
    string B = "World\r\nWorld\nWorld";

    Console.WriteLine(ConcatMultilineString(A, B));

    Console.ReadLine();

}

输出:

Hello_World
Hello_World
Hello_World

我认为通用的方法是不可能的,如果你要加载从不同平台创建的字符串(Linux + Mac + Windows)或者甚至得到字符串包含 HTML 换行符或其他任何内容 我想你必须自己定义换行符。

string a = getA();
string b = getB();
char[] lineBreakers = {'\r', '\n'};
char replaceWith = '\n';
foreach(string lineBreaker in lineBreakers)
{
    a.Replace(lineBreaker, replaceWith);
    b.Replace(lineBreaker, replaceWith);
}
string[] as = a.Split(replaceWith);
string[] bs = a.Split(replaceWith);
string newLine = Environment.NewLine; 
if(as.Length == bs.Length)
{
    return as.Zip(bs (p, q) => $"{p}{q}{newLine }")
}