我正在尝试编写一个代码,根据字符索引合并两个字符串。例如,如果我们有两个字符串" abc"和" defg",我想要一个字符串output1(合并两个字符串的所有偶数字符)=" 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();
}
}
但是在这种情况下它会给出绑定数组异常之外的内容。有没有更好的方法呢?
由于
答案 0 :(得分:2)
我建议提取一个方法,你应该解决广义问题合并两个字符串,从step
开始从中获取每个offset
字符:
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);
答案 1 :(得分:0)
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)
{
if(a.Length > l)
{newstring += a[l].ToString();}
newstring += b[l].ToString();
}
if (l % 2 == 1)
{
if(a.Length > l)
{newstring1 += a[l].ToString();}
newstring1 += b[l].ToString();
}
}
Console.ReadLine();
}
}
答案 2 :(得分:0)
for (int l = 0; l < b.length && l < a.length; l++)
{
if(l%2==0)
{
newstring += a[l]+ b[l];
}
if (l % 2 == 1)
{
newstring1 += a[l] + b[l];
}
}