2014-09-22 65 views
-2

我有以下字符串:分割字符串成2 C#塊

  string input ="this is a testx"; 

我需要把空格去掉,然後拆分輸入兩個大塊,這樣我就可以單獨每兩個字母的過程:

th的是在ES TX

我試圖與刪除空格:

input=input.Remove(input.IndexOf(' '),1); 

Ť母雞我不能做與分裂...

+0

什麼代碼中有你試過嗎?你是否收到異常或不正確的結果? – 2014-09-22 00:25:22

+2

問題是什麼? – Dmitry 2014-09-22 00:25:33

回答

4
IEnumerable<string> output = input 
    .Replace(" ", string.Empty) 
    .Select((ch, i) => new{ch, grp = i/2}) 
    .GroupBy(x => x.grp) 
    .Select(g => string.Concat(g.Select(x => x.ch))); 

或更理智:)

input = input.Replace(" ", string.Empty); 
IEnumerable<string> output = 
    Enumerable.Range(0, input.Length/2).Select(x => input.Substring(x * 2, 2)); 

,你可以按如下方式使用輸出:

foreach(var item in output) 
{ 
    Console.WriteLine(item); 
} 
+2

那一刻,當2行'for'換成5行LINQ時:-) – zerkms 2014-09-22 00:28:30

+0

我對編程相對比較陌生,我從來沒有用過LINQ之前:( 我不懂整個代碼 – WaelT 2014-09-22 00:31:51

+0

@zerkms我遇到過我希望我的第二種方法可以彌補:-) – spender 2014-09-22 00:33:37