Home > Software design >  Why did the output repeate again in some substring?
Why did the output repeate again in some substring?

Time:12-03

    #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?

CodePudding user response:

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;

LIVE

CodePudding user response:

The reason this is happening is because j is always being set to n. You are telling substr to give you n counts past i which is not what you want. You want from i to the end of the string and then decrease from there.

Change from for (int j = n; j > i; j--)

to for (int j = (n - i); j > 0; j--)

  • Related