使用循环将字符串拆分为特定长度的子单元 [英] Split string using loop to specific length sub-units
问题描述
我需要将字符串拆分为特定长度,例如如果用户将其指定为最大长度为4的单位,则循环应在原始输入"0123456789asdf"
上运行以获取"0123"
,"4567"
,"89as"
,"df"
.
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"
.
我无法真正找到执行此操作的最佳方法-我需要使其处于循环状态,因为需要对增强对象的每个子单元进行进一步处理. TIA.
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:我不知道原始字符串有多长,而且我只知道它需要变成的块的大小.另外,我需要指定长度的字符串块,以及最后一个包含字符串 remainder 的块(如果小于指定长度).
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).
推荐答案
string str("0123456789asdf");
for (unsigned i = 0; i < str.length(); i += 4) {
cout << str.substr(i, 4) << endl;
}
这篇关于使用循环将字符串拆分为特定长度的子单元的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!