Splitting a string into chunks of a certain size

后端 未结 30 2003
时光说笑
时光说笑 2020-11-22 07:55

Suppose I had a string:

string str = \"1111222233334444\"; 

How can I break this string into chunks of some size?

e.g., breaking t

30条回答
  •  [愿得一人]
    2020-11-22 08:19

    Modified (now it accepts any non null string and any positive chunkSize) Konstantin Spirin's solution:

    public static IEnumerable Split(String value, int chunkSize) {
      if (null == value)
        throw new ArgumentNullException("value");
      else if (chunkSize <= 0)
        throw new ArgumentOutOfRangeException("chunkSize", "Chunk size should be positive");
    
      return Enumerable
        .Range(0, value.Length / chunkSize + ((value.Length % chunkSize) == 0 ? 0 : 1))
        .Select(index => (index + 1) * chunkSize < value.Length 
          ? value.Substring(index * chunkSize, chunkSize)
          : value.Substring(index * chunkSize));
    }
    

    Tests:

      String source = @"ABCDEF";
    
      // "ABCD,EF"
      String test1 = String.Join(",", Split(source, 4));
      // "AB,CD,EF"
      String test2 = String.Join(",", Split(source, 2));
      // "ABCDEF"
      String test3 = String.Join(",", Split(source, 123));
    

提交回复
热议问题