s1="Mark"; s2="Zukerberg"; //Output=> MZaurkkerberg
如果:
s1="Zukerberg"; s2="Mark" //Output=> ZMuakrekrberg
如果:
s1="Zukerberg"; s2="Zukerberg"; //Output=> ZZuukkeerrbbeerrgg
我写了下面的代码,它给出了预期的输出,但它似乎是很多代码.有没有更有效的方法来做到这一点?
public voID SpecialConcat(string s1,string s2) { string[] concatArray = new string[s1.Length + s2.Length]; int k = 0; string final = string.Empty; string superFinal = string.Empty; for (int i = 0; i < s1.Length; i++) { for (int j = 0; j < s2.Length; j++) { if (i == j) { concatArray[k] = s1[i].ToString() + s2[j].ToString(); final = string.Join("",concatArray); } } k++; } if (s1.Length > s2.Length) { string subOne = s1.Remove(0,s2.Length); superFinal = final + subOne; } else if (s2.Length > s1.Length) { string subTwo = s2.Remove(0,s1.Length); superFinal = final + subTwo; } else { superFinal = final; } Response.Write(superFinal); } }
我也在JavaScript中编写了相同的逻辑,它工作正常,但又有很多代码.
解决方法var s1 = "Mark";var s2 = "Zukerberg";var common = string.Concat(s1.Zip(s2,(a,b) => new[]{a,b}).SelectMany(c => c));var shortestLength = Math.Min(s1.Length,s2.Length);var result = common + s1.Substring(shortestLength) + s2.Substring(shortestLength);总结
以上是内存溢出为你收集整理的c# – 两个字符串的特殊连接的更好方法全部内容,希望文章能够帮你解决c# – 两个字符串的特殊连接的更好方法所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)