tags:

views:

120

answers:

4

The following program replaces all spaces with %20.the compilation works fine but the program terminates during the runtime.Any help???

#include<iostream>
#include<string>
using namespace std;

void removeSpaces(string url){

int len=url.length();
int i,count=0;
while(i<=len){
if(url[i]==' ')
count++;
i++;
}
int length2=len+(count*2);
string newarr[length2];
for(int j=len-1;j>=0;j--){
if(url[j]==' ')
{
  newarr[length2-1]='0';
  newarr[length2-2]='2';
  newarr[length2-3]='%';
  length2=length2-3;
}
else
{
  newarr[length2-1]=url[j];
  length2=length2-1;
}
}
cout<<"\nThe number of spaces in the url is:"<<count;
cout<<"\nThe replaced url is:"<<newarr;

}

int main(){

string url="http://www.ya h o o.com/";
removeSpaces(url);
}
+3  A: 

This is called an "off by one" error.

while(i<=len){
    if(url[i]==' ')

I'd also look at std::string::find() and std::string::replace() rather than what you're doing.

EDIT: Since the poster has said this isn't homework:

for (size_t pos = myString.find(' '); 
     pos != string::npos; 
     pos = myString.find(' ', pos))
{
    myString.replace(pos, 1, "%20");
}
Brian Roach
+1  A: 
string newarr[length2];

should be:

string newarr;

or

char newarr[length2];

or the more proper way:

char *newarr = new char[length2];
... // code.
delete[] newarr;
zipcodeman
The last way is the least proper way as it is not exception safe. Use a vector rather than dynamically allocating an array of characters.
Martin York
@Martin York: Well, the variable length char array isn't even standard C++, so I'd say that's pretty improper.
Maulrus
+3  A: 

i is not initialized to 0 - this is the danger if using ',' instead of putting each variable on its own line.

Michael Dorgan
+2  A: 

As long as you're using string and not char *, why not use the string methods? This is essentially a translation of what you're trying to do (without even using ::find or ::replace):

void removeSpaces(string url)
{
    string newUrl;
    int count = 0;

    for (int j = 0; j < url.length(); ++j)
    {
        if (url.at(j) == ' ')
        {
            newUrl.append("%20");
            ++count;
        }
        else
            newUrl.append(url.at(j));
    }

    cout << "\nThe number of spaces in the url is:" << count;
    cout << "\nThe replaced url is:"<< newUrl;
}

Edit: I see that @Bryan has given the version with ::find and ::replace.

egrunin
Yeah, for efficiency I should have run the find() only from the last pos ... but I figured that should at least point him in the right direction. And we all know that premature optimization is bad :-D
Brian Roach