我正在尝试编写代码以根据字符索引合并两个字符串。例如,如果我们有两个字符串“abc”和“defg”,我想要一个字符串输出 1(合并两个字符串的所有偶数字符) ="adcf"和另一个字符串 output2="beg"(剩下的所有单词)。
我尝试了什么-
class Program
{
static void Main(string[] args)
{
string a= "First";
string b= "MiddleName";
string newstring = "";
string newstring1 = "";
int length = b.Length;
for (int l = 0; l < length; l=l+1)
{
if(l%2==0)
{
newstring = newstring + a[l].ToString() + b[l].ToString();
}
if (l % 2 == 1)
{
newstring1 = newstring1 + a[l].ToString() + b[l].ToString();
}
}
Console.ReadLine();
}
}
但是在这种情况下,它会在绑定(bind)数组之外给出异常。有没有更好的方法来做到这一点?
谢谢
最佳答案
我建议提取一个方法,您应该在其中解决合并两个字符串的一般性问题,从开始,每个
:step
个字符>偏移量
private static String Merge(String left, String right, int step, int offset) {
StringBuilder sb = new StringBuilder();
if (null == left)
left = ""; // or throw exception
if (null == right)
right = ""; // or throw exception
for (int i = offset; i < Math.Max(left.Length, right.Length); i += step) {
//DONE: do not forget to check if you can get a character
if (i < left.Length)
sb.Append(left[i]);
//DONE: do not forget to check if you can get a character
if (i < right.Length)
sb.Append(right[i]);
}
return sb.ToString();
}
所以你可以这样说
String a = "abc";
String b = "defg";
// adcf
String output1 = Merge(a, b, 2, 0);
// beg
String output2 = Merge(a, b, 2, 1);
关于c# - 根据字符索引合并两个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37675550/