Asked  6 Months ago    Answers:  5   Viewed   32 times

Suppose I had a string:

string str = "1111222233334444"; 

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

e.g., breaking this into sizes of 4 would return strings:

"1111"
"2222"
"3333"
"4444"

 Answers

85
static IEnumerable<string> Split(string str, int chunkSize)
{
    return Enumerable.Range(0, str.Length / chunkSize)
        .Select(i => str.Substring(i * chunkSize, chunkSize));
}

Please note that additional code might be required to gracefully handle edge cases (null or empty input string, chunkSize == 0, input string length not divisible by chunkSize, etc.). The original question doesn't specify any requirements for these edge cases and in real life the requirements might vary so they are out of scope of this answer.

Tuesday, June 1, 2021
 
Maury
answered 6 Months ago
56

http://en.wikipedia.org/wiki/Ascii#ASCII_control_code_chart

Binary   Oct  Dec    Hex    Abbr    Unicode  Control char  C Escape code   Name
0000000  000  0      00     NUL     ?       ^@                          Null character

There's no difference, but the more idiomatic one is ''.

Putting it down as char c = 0; could mean that you intend to use it as a number (e.g. a counter). '' is unambiguous.

Tuesday, June 22, 2021
 
samrap
answered 6 Months ago
92

It may be more sensible to match the characters and then join them:

str = str.match(/(d+|[^d]+)/g).join(',');

But don't omit the quotes when you define the string:

var str = 'A123B234C456';
Wednesday, July 7, 2021
 
KingCrunch
answered 5 Months ago
54

Use String#scan:

>> 'abcdefghijklmnopqrstuvwxyz'.scan(/.{4}/)
=> ["abcd", "efgh", "ijkl", "mnop", "qrst", "uvwx"]
>> 'abcdefghijklmnopqrstuvwxyz'.scan(/.{1,4}/)
=> ["abcd", "efgh", "ijkl", "mnop", "qrst", "uvwx", "yz"]
>> 'abcdefghijklmnopqrstuvwxyz'.scan(/.{1,3}/)
=> ["abc", "def", "ghi", "jkl", "mno", "pqr", "stu", "vwx", "yz"]
Saturday, July 31, 2021
 
Daniel H
answered 4 Months ago
22

Apart from what you're doing is probably best done with XML APIs instead of strings or StringBuilder I doubt that the error you see is due to string concatenation. Maybe switching to StringBuilder just masked the error or went over it gracefully, but I doubt using strings really was the cause.

Friday, August 6, 2021
 
rlanvin
answered 4 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share