使用循环将字符串拆分为特定长度的子单元

scc*_*ccs 8 c++ loops substr

我需要的,如果用户它指定最大长度4为单位的字符串分割成特定的长度,例如,则循环应在原始输入运行"0123456789asdf"得到"0123","4567","89as","df".

我无法找到最好的方法 - 我需要它在循环中,因为需要在强大的每个子单元上进行进一步的处理.TIA.

编辑:我不知道原始字符串有多长,我只知道它需要变成的块的大小.此外,我需要指定长度的字符串块,以及包含字符串其余部分的最后一个块(如果它小于指定的长度).

小智 24

string str("0123456789asdf");

for (unsigned i = 0; i < str.length(); i += 4) {
    cout << str.substr(i, 4) << endl;
}
Run Code Online (Sandbox Code Playgroud)