Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why did the output repeate again in some substring?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;

LIVE

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading