Splitting string into pairs with c#

前端 未结 6 441
后悔当初
后悔当初 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:05

    List result = new List();
    
    while (original.Length > 0)
    {
        result.Add(new String(original.Take(2).ToArray()));
        original = new String(original.Skip(2).ToArray());
    }
    
    return result;
    

    The LINQ probably uses indices somewhere internally, but I didn't touch any of them so I consider this valid. It works for odd-length originals, too.

    Edit:

    Thanks Heinzi for the correction. Demo: http://rextester.com/MWCKYD83206

提交回复
热议问题