Splitting string into pairs with c#

前端 未结 6 492
后悔当初
后悔当初 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 02:07

    1) Split list into pairs

    var s = "TVBMCVTVFGTVTB";
    var pairs = Enumerable.Range(0, s.Length / 2)
                          .Select(i => String.Concat(s.Skip(i * 2).Take(2)));
    

    This will work if you know that s always is of even length, or you don't accept, or don't care about, ending with singletons for strings with odd length.

    2) Split list into pairs - include any singleton remainders

    If you want to include singleton remainders, for odd length strings, you can simply use ceiling:

    var s = "TVBMCVTVFGTVTB";
    var pairs = Enumerable.Range(0, (int)Math.Ceiling(s.Length / 2D))
                          .Select(i => String.Concat(s.Skip(i * 2).Take(2)));
    

提交回复
热议问题