Gutierza
Gutierza

Reputation: 27

How do I insert spaces back into string after removing them

I am trying to : 1) Remove spaces from a given string 2) From the removed spaces string, insert the spaces to where they were original 3) Final result should be the original text.

string original = "The quick brown fox jumps over the lazy dog"; string removeSpace, withSpace;

int foo[8];
int count = 0;

cout << original << endl;

for (int i = 0; i < original.size(); i++)
{
    if (char(int(original[i])) == 32)
    {
        foo[count] = i;

        count++;
    }
    else
    {
        removeSpace += original[i];
    }
}
cout << endl;
for (int i = 0; i < 8; i++)
{
    cout << "Spaces at : " << foo[i] << endl;
}
cout << "==========With spaces remove==========" << endl;
cout << removeSpace << endl;
count = 0;

for (int i = 0; i < removeSpace.size(); i++)
{
    if (foo[count] == i)
    {
        withSpace += ' ';
        count++;

    }
    withSpace += removeSpace[i];
}

cout << "==========With spaces inserted==========";
cout << "\n" << withSpace << endl;

This is what i am getting:

The quickb rownfo xjum psover thela zydo g

How do I insert them back to make it "The quick brown fox jumps over the lazy dog"

Upvotes: 0

Views: 326

Answers (1)

john
john

Reputation: 87959

It's clear what the problem is from looking at your output. In foo you are storing the indexes of the spaces before any spaces have been removed. But when you put back the spaces you are comparing foo with i which is the index after the spaces have been removed. This is not a meaningful thing to do. You just need to adjust your algorithm to account for this difference.

Here's a minimal adjustment to your code that fixes the problem. By comparing foo[cout] with the size of the withSpace string I'm comparing like with like. Both foo[count] and withSpace.size() are indexes and sizes of the string after spaces have been added.

for (int i = 0; i < removeSpace.size(); i++)
{
    if (foo[count] == withSpace.size())
    {
        withSpace += ' ';
        count++;
    }
    withSpace += removeSpace[i];
}

Full code here.

This code

if (char(int(original[i])) == 32)

is a good example of doing a simple thing in a complicated way. This is better

if (original[i] == ' ')

Upvotes: 3

Related Questions