Splitting string into pairs with c#

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

    Oh come on, just use indexes like this:

    public static class StringExtensions {
        public static IEnumerable TakeEvery(this string s, int count) {
            int index = 0;
            while(index < s.Length) {
                if(s.Length - index >= count) {
                    yield return s.Substring(index, count);
                }
                else {
                    yield return s.Substring(index, s.Length - index);
                }
                index += count;
            }
        }
    }
    

    I have added no guard clauses.

    Usage:

    var items = "TVBMCVTVFGTVTB".TakeEvery(2);
    foreach(var item in items) {
        Console.WriteLine(item);
    }
    

提交回复
热议问题