#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string s = "abcdefg";
int n = s.size();
for (int i = 0; i < n; i++)
{
for (int j = n; j > i; j--)
{
std::cout << s.substr(i,j) << std::endl;
}
}
}
I want to output substring from abcdefg, abcdef,... a, then, bcdefg, bcdef...b,.
However, the result shows it is repeated in some part, for example, cdefg repeated three times in my result, why and how to correct it?
>Solution :
The 2nd parameter of substr is supposed to be count, i.e. the length of the substring, so change
std::cout << s.substr(i,j) << std::endl;
to
std::cout << s.substr(i,(j-i)) << std::endl;