Question

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.

Was it helpful?

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] + " ";
            }

OTHER TIPS

this works

#include <iostream>
#include <string>

using namespace std;

string AddSpaceToString (string input)
{
    const int arrLength = 5;
    unsigned int lastFind = 0;
    string output;
    string dictionary[arrLength] = {"hello", "hey", "whats", "up", "man"};

    for (int j = 0; lastFind < input.size() && j < arrLength; ++j)
    {       

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

    return output;
}

int main ()
{
    cout << AddSpaceToString("heywhatshelloman") << endl;

    return 0;
} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top