Splitting string into pairs with c#

前端 未结 6 440
后悔当初
后悔当初 2021-01-28 01:26

Is there a way to break a string into pairs without looking at indexes? e.g. TVBMCVTVFGTVTB would be broken into a list of strings as such:

[TV,BM,CV,TV,FG,TV,TB]

<
6条回答
  •  一生所求
    2021-01-28 01:54

    If you like some esoteric solutions:

    1)

    string s = "TVBMCVTVFGTVTB";
    var splitted = Enumerable.Range(0, s.Length)
                             .GroupBy(x => x / 2)
                             .Select(x => new string(x.Select(y => s[y]).ToArray()))
                             .ToList();
    

    2)

    string s = "ABCDEFGHIJKLMN";
    var splitted = Enumerable.Range(0, (s.Length + 1) / 2)
                             .Select(i => 
                                     s[i * 2] + 
                                     ((i * 2 + 1 < s.Length) ? 
                                     s[i * 2 + 1].ToString() : 
                                     string.Empty))
                             .ToList();
    

提交回复
热议问题