Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Adding Spaces to String

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.

like image 843
ScottOBot Avatar asked Sep 13 '26 13:09

ScottOBot


1 Answers

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] + " ";
            }
like image 118
Abhishek Bansal Avatar answered Sep 16 '26 04:09

Abhishek Bansal