9

I need to split a string into specific lengths, e.g. if user specifies it to units of max length 4, then the loop should run on the original input "0123456789asdf" to get "0123", "4567", "89as", "df".

I can't really figure out the best way to do this - and I need it to be in a loop as further processing needs to be done on each subunit of the strong. TIA.

edit: I do not know how long the original string is, and I only know the size of the chunk it needs to become. Also, I need chunks of the string of the specified length, and the last chunk containing the remainder of the string (if it is less than the specified length).

sccs
  • 1,123
  • 3
  • 14
  • 27
  • a similar question that probably could help you: [C++: How do I split a string into evenly-sized smaller strings?](http://stackoverflow.com/questions/8207730/c-how-do-i-split-a-string-into-evenly-sized-smaller-strings) – t.niese May 23 '13 at 08:46

2 Answers2

27
string str("0123456789asdf");

for (unsigned i = 0; i < str.length(); i += 4) {
    cout << str.substr(i, 4) << endl;
}
Croniak
  • 664
  • 5
  • 4
0

std::string can take a range as its constructor argument (constructor 6). Use it:

char const str[] = "0123456789asdf";
std::string x(str, str + 4); // "0123"

Here, str and str + 4 are pointers to characters into the char array, which are compatible with the ForwardIterator concept. (Pointers are iterators)

slaphappy
  • 6,894
  • 3
  • 34
  • 59