2016-11-29 68 views
2

我想創建一個字符串,下面是我想實現的東西:我想創建最終的字符串這樣拆分和合並兩個不同的字符串

String first = "Previous.value1 | Previous.value2"; 
String second = "New.value1| New.value2"; 

string final ="generate Previous.value1 cross New.value1 ? Previous.value1 cross New.value2"; 

但問題是,當我將有不匹配象下面這樣:

String first = "Previous.value1 | Previous.value2"; 
String second = "New.value1"; 

然後我想有這樣的,因爲我沒有匹配值Previous.Value2第二個變量

string final ="generate Previous.value1 cross New.value1"; 

到目前爲止,我成功我在最後生成字符串時,我在的價值相同的計數這兩個字符串。

string final = "generate"; 
if (first.Split('|').Count() - second.Split('|').Count() == 0) 
{ 
    int i = 0; 
    foreach (var item in first.Split('|').Count()) 
    { 
     if (i == 0) 
      final = final + item + " cross " + second.Split('|')[i]; 
     else 
      final = final + " ? " + item + " cross " + second.Split('|')[index]; 
     i++; 
    } 
} 
+2

那麼是什麼問題? – PMerlet

+1

if(second.Contains(「|」)){//做點什麼} –

+0

@TimSchmelter:我已經更新了我的問題的變化。好吧 –

回答

3

試試這個LINQ查詢(使用the Zip extension method):

var zippedQry = first.Split('|').Zip(second.Split('|'), 
    (f, s) => f.Trim() + " cross " + s.Trim()); 
string final = "generate " + String.Join(" ? ", zippedQry.ToArray()); 
+1

你能請給我解釋一下你的代碼最重要的zip函數學習這種新的壓縮功能及其usage.please –

+1

有關拉鍊功能的詳細信息,請點擊我在我的文章中提供的鏈接。它基本上需要兩個單獨的列表(在你的情況下分割字符串),並將它們組合成一個列表以選擇(在你的情況下創造了「跨界」文本)。在第二行中,組合列表連接到一個字符串。 – Sefe

+0

不過這個功能在這種情況下怎麼做的行爲:第一串=「Previous.value1 | Previous.value2」; String second =「New.value1」;。你能解釋一下這個輸入嗎? –

1

留在你使用的風格,我會建議先拆兩個字符串

String first = "Previous.value1 | Previous.value2"; 
String second = "New.value1 | New.value2"; 
string final = "generate "; 

string[] first_values = first.Split('|'); 
string[] second_values = second.Split('|'); 

然後你就可以只需定位在最短的陣列上即可。如果你在爲first_values的不夠的對應值有你只收集相應的。使用普通的for循環:

// run until the length of the shortest one 
for (int i = 0; i < Math.Min(first_values.Length, second_values.Length); i++) 
{ 
    // bild the normal cross-version for the first position 
    string sentence = first_values[i] + " cross " + second_values[i]; 
    // if on first position use normal version otherwise put a ? infront of it 
    final += i == 0 ? sentence : " ? " + sentence; 
} 

這個循環也應該處理的字符串是這樣的:

String first = "Previous.value1 | Previous.value2 | Previous.value3 | Previous.value4"; 
String second = "New.value1 | New.value2 | New.value3"; 
+0

非常感謝您的答覆和您的善意幫助:) –