0

I am trying to print all substring of string but this function not printing all substring can you explain whats wrong?

require o/p= >

a
ab
abc
b
bc
c

curr o/p=>

a
ab
abc
b
void subString(string s, int n)
{

    for (int i = 0; i < n; i++) {
        for (int len = 1; len <= n - i; len++) {

            string str;

            for (int k = i; k < len; k++) {
                str += s[k];
            }
            if (str != "")
                cout << str << endl;
        }
    }
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • I assume that by `string` you mean `std::string` as defined in the `` header? – PieterNuyts Jan 08 '21 at 13:11
  • The expected solution here should have exactly two `for` loops. Not three. The shown logic must be fundamentally flawed. – Sam Varshavchik Jan 08 '21 at 13:14
  • Does the argument `n` indicate the length of the string `s`? You could just get that using `s.size()`. – PieterNuyts Jan 08 '21 at 13:14
  • @SamVarshavchik The third one just copies char from one string into another. There may be more efficient ways to do this, but it doesn't look like flawed logic. – PieterNuyts Jan 08 '21 at 13:16
  • Does this answer your question? [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – Kanony Jan 08 '21 at 13:17

1 Answers1

3

k is initialized with i (trying to use index in overall string), but the loop condition is compared to len (trying to use index in current substring). This is contradiction. Use either one index.

Use index in overall string:

            for (int k = i; k < i + len; k++) {
                str += s[k];
            }

Use index in current substring:

            for (int k = 0; k < len; k++) {
                str += s[i + k];
            }

Another way is to use the standard substr() (assuming string here is std::string):

            str = s.substr(i, len);
MikeCAT
  • 73,922
  • 11
  • 45
  • 70