Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
117 views
in Technique[技术] by (71.8m points)

c++ - Split string using loop to specific length sub-units

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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
string str("0123456789asdf");

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...