我有一个相当困难的问题,我不确定我该如何做需要做的事情。
我有两个string
,text1
和text2
。我需要创建一个基于两者 的结果
。 text2
有分隔符 "|"
因此如果 text1
中有三个字符那么就会有 两个 分隔符等.
我需要创建一个 result
,它是 text2
,没有分隔符,并且用 text1
中的相应字符替换 #
。下面我有一些例子:
text1: 間違う text2: ま|ちが|# result: まちがう
text1: 立ち上げる text2: た|#|あ|#|# result: たちあげる
text1: 取る text2: と|# result: とる
将不胜感激意见和建议。
最佳答案
如果我没理解错的话,你想将 text2
中的每个 #
替换为 text1
中对应的字符处理 |
作为分隔符;
您可以在 Linq 的帮助下完成此操作:
代码:
private static String ProcessString(string text1, string text2) {
return string.Concat(text2
.Split('|')
.Select((item, index) => item == "#"
? text1[index].ToString() // substitute with corresponding char from text1
: item)); // keep as it is
}
演示:
Tuple<string, string>[] tests = new[] {
Tuple.Create("間違う", "ま|ちが|#"),
Tuple.Create("立ち上げる", "た|#|あ|#|#"),
Tuple.Create("取る", "と|#"),
};
var result = string.Join(Environment.NewLine, tests
.Select(test =>
$"{test.Item1,5} + {test.Item2,10} => {ProcessString(test.Item1, test.Item2)}"));
Console.WriteLine(result);
结果:
間違う + ま|ちが|# => まちがう
立ち上げる + た|#|あ|#|# => たちあげる
取る + と|# => とる
关于c# - 如何根据替换字符将一个字符串的值替换为另一个字符串的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58214947/