C++ - Adding Spaces to String

c++, parsing, string, substr

Solution

After reading `"hey"` and `"whats"`, the value of `i` is more than the length of `"hello"` and hence no such substring exists for the code `input.substr(lastFind, i)`.

You should check for the length of possible substring (`dictionary[j]`) and not `i`.

input.substr( lastFind, dictionary[j].size() )

Also you will have to change:

lastFind += dictionary[j].size();

So the if loop becomes:

if(dictionary[j] == input.substr(lastFind, dictionary[j].size() ))
            {
                lastFind += dictionary[j].size();
                output += dictionary[j] + " ";
            }

Problem

Hey so I am trying to write a simple program that adds spaces to a given string that has none in C++ here is the code I have written: ``` #include <iostream> #include <string> using namespace std; string AddSpaceToString (string input) { const int arrLength = 5; int lastFind = 0; string output; string dictionary[arrLength] = {"hello", "hey", "whats", "up", "man"}; for (int i = 0; i < input.length(); i++) { for (int j = 0; j < arrLength; j++) { if(dictionary[j] == input.substr(lastFind, i)) { lastFind = i; output += dictionary[j] + " "; } } } return output; } int main () { cout << AddSpaceToString("heywhatshelloman") << endl; return 0; } ``` For some reason the output only gives `hey whats` and then stops. What is going on I can't seem to make this very simple code work.

Original source