2016-06-07 132 views
3

我想写一个代码来合并基于字符索引的两个字符串。例如,如果我们有两个字符串“abc”和“defg”,我想要一个字符串output1(合并两个字符串的所有偶数字符)=“adcf”和另一个字符串output2 =“beg”(剩下的所有单词)。基于字符索引合并两个字符串

我tried-什么

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(); 
     } 


    } 

但随后在这种情况下,它会给绑定阵列外exception.Any更好的方式来做到这一点?

感谢

+0

你'length'必须是短字符串长度,在循环之后,将来自较长字符串的所有剩余字符追加到'newstring1'。 –

+0

但它不会采取长字符串 – vic90

+0

的所有偶数字符for(int l = 0; l mohsen

回答

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); 
+0

非常感谢Sir.Great idea – vic90

0

它发生是因为B比A更长的词。所以当它的迭代大于A'的长度时,它会导致错误。 所以你需要检查是否有那么多的话,将其添加 之前,如果B”的长度总是大于A,那么你可以使用波纹管代码

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(); 
    } 


} 
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]; 
     } 
}