Splitting a string into chunks of a certain size

后端 未结 30 2030
时光说笑
时光说笑 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:15

    How's this for a one-liner?

    List result = new List(Regex.Split(target, @"(?<=\G.{4})", RegexOptions.Singleline));
    

    With this regex it doesn't matter if the last chunk is less than four characters, because it only ever looks at the characters behind it.

    I'm sure this isn't the most efficient solution, but I just had to toss it out there.

提交回复
热议问题