问题
I have a rather difficult problem and I'm not sure how I can do what is needed.
I have two strings, text1 and text2. I need to create a result that is based on both of these. text2 has separator "|" so that if there are three characters in text1 then there will be two separators etc.
I need to create a result that is text2 without the separator and with a the corresponding character from text1 replacing the #. Below I have some examples:
text1: 間違う text2: ま|ちが|# result: まちがう
text1: 立ち上げる text2: た|#|あ|#|# result: たちあげる
text1: 取る text2: と|# result: とる
Would appreciate advice and suggestions.
回答1:
If I understand you right, you want to substitute each # within text2 into corresponding character in text1 treating | as a delimiter;
you can do it with a help of Linq:
Code:
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
}
Demo:
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);
Outcome:
間違う + ま|ちが|# => まちがう
立ち上げる + た|#|あ|#|# => たちあげる
取る + と|# => とる
来源:https://stackoverflow.com/questions/58214947/how-can-i-substitute-the-value-of-one-string-into-another-based-on-a-substitutio