3

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.

2 Answers 2

3

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] + " ";
            }
Sign up to request clarification or add additional context in comments.

1 Comment

Hey thanks for the solution, I was under the assumption the substr() function's first parameter was the start position of the string and the second was the end position where in reality its the start position and the length. Thanks for the help I got it to work with your answer @AbhishekBansal
1

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

1 Comment

Nice getting rid of the second loop much more efficient O(N) nice! is it tested? @Julius

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.