andreahmed andreahmed - 3 months ago 16
C++ Question

Generating substrings in c++

I'm trying to generate all the substrings of the word fun.

But it prints "un" two times, I don't know why.

int c, i;
string s = "fun";
for (c = 0; c < s.length(); c++)
{
for (i = c+1; i <= s.length(); i++)
{
string d = s.substr(c, i);
cout << d << endl;
}
}

Answer

The second parameter to substr is length, not the ending index of the sub-string.

You can use the following logic to get all sub-strings:

  • Start from index 0, select the substring of length 1, then of length 2, then 3 and so on
  • Then move on to index 1 and perform the same to it and so on. (When at index 1, the remaining length of the string would be 2, in case of fun, so we'd have to run the loop till length 2)

    string s = "fun";
    for (int c = 0; c < s.length(); c++)
    {
        for (int i = 1; i <= s.length() - c; i++)
        {
            string d = s.substr(c, i);
            cout << d << endl;
        }
    }