C#将一个逗号分隔的字符串换置为另一个

问题描述 投票:-1回答:1

我想将值从一个逗号分隔的字符串转换为另一个逗号分隔的字符串。

示例1

Input 1 : 1,19,2,20,3,30
Input 2 : ,,{0},{1},,

Output  : ,,2,20,,

示例2

Input 1 : 1,19,2,20,3,30
Input 2 : ,,,,{0},{1}

Output  : ,,,,3,30

两个输入字符串的开头都有一些其他值。因此,如果有任何逻辑从头算起对我有利。

我实际上有一个字符串列表,其中包含输入2值之类的模式。然后需要将输入1的值移置到所有具有模式的字符串上,例如输入2。

谢谢,罗汉。

c# linq lambda
1个回答
0
投票

您可以执行以下操作:

void Main()
{
    Console.WriteLine(
    TransformCustom("1,19,2,20,3,30",",,{ 0},{ 1},,")
    );

//Output: ,,2,20,,
Console.WriteLine(
TransformCustom("1,19,2,20,3,30",",,,,{ 0},{ 1}")
);

//Output: ,,,,3,30
}

private string TransformCustom(string input1, string input2)
{
    return string.Join(",",
    input1.Split(',').Zip(input2.Split(','), (i1, i2) => new {i1, i2})
        .Select(i => string.IsNullOrEmpty(i.i2)?"":i.i1));
}
© www.soinside.com 2019 - 2024. All rights reserved.