2016-06-07 131 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]; 
     } 
}