How can I substitute the value of one string into another based on a substitution character?

北城以北 提交于 2021-02-17 03:28:31

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!