0
Write substrings of the string!
String s="abcdefgh", I would like to get these substrings a, b, c, d, e, f, g, h, ab, cd, ef, gh, abc, def, abcd, efgh, abcde, abcdef, abcdefg, abcdefgh. I need your help to do do this.
7 Answers
+ 2
Buterbrod:) indeed, I am wrong. Somehow I had misread the example pattern as only a, ab, abc, ..., abcdefgh. Now I see the start position shifts, too, and the substring is not printed if the length is less than the exact count.
TeaserCode I apologize for misleading you. The pattern requires a minimum of two loops.
FYI, The warning in your code can be cleared by casting i3 as (unsigned) in the conditional on line 27.
+ 1
You can use 2 for loops
// first to find out how many
// letters in a string to cut
for (;;) {
// the second one, to cut out the number
// of letters that the first loop gives
for (;;) {
// some code ...
}
}
+ 1
Brian you are completely wrong. If you use only one loop, you will not know from which next index to take the substring.
This is how it should look for two characters:
abcdefgh -> ab, cd, ef, gh
But if we take the code from your example, we will always cut the string starting from the first index, which is wrong
// with `cout << s.substr(0, i) << endl;`
abcdefgh -> a, ab, abc, abcd, abcde, ancdef, ...
+ 1
Thank you all for your answers, I have done it sucessfully, see "string subpattern recognition I".
0
TeaserCode you may use nested loops as Buterbrod:) recommended. Or you may use a single loop and use the substr(start, len) string method call, where the substring length is given by the loop index.
cout << s.substr(0, i) << endl;
0
How many loops should it be used at least?
0
TeaserCode think about how loops would be used.
At least one loop is needed to increment for however many substrings will be printed.
Inside that loop it prints a substring made up of a limited number of characters. You may use a nested loop that prints one character at a time up to the desired number of characters. Or, instead of a loop, you may use .substr() that returns a substring of the desired length so you can print all the characters at once.
If you have trouble getting either of theses approaches to work then post a link to the code and we'll help further.