2010-04-22 172 views
1

以下程序用%20替换所有空格。编译工作正常,但程序在运行时期间终止。任何帮助???用%20替换空格

#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); 
} 
+1

你为什么要声明一个字符串_array_? – SLaks 2010-04-22 00:19:09

+0

这是功课吗?它应该有'家庭作业'标签。 – 2010-04-22 00:26:11

+0

没有面试Q – Jony 2010-04-22 00:30:13

回答

5

这被称为“off by one”错误。

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

我也想看看std::string::find()std::string::replace(),而不是你在做什么。

编辑:由于海报说,这不是功课:

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

应该是:

string newarr; 

char newarr[length2]; 

或更多正确的方法:

char *newarr = new char[length2]; 
... // code. 
delete[] newarr; 
+0

最后一种方式是最不合适的方式,因为它不是例外。使用矢量而不是动态分配字符数组。 – 2010-04-22 00:43:16

+0

@Martin York:那么,可变长度的char数组甚至不是标准的C++,所以我会说这很不合适。 – Maulrus 2010-04-22 00:51:43

3

我没有初始化为0 - 这是如果使用','而不是将每个变量放在它自己的行上的危险。

2

只要您使用的是string而不是char *,为什么不使用string方法呢?这基本上是你正在试图做的(甚至不需要使用::find::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; 
} 

编辑:我看到@Bryan给了版本::find::replace

+0

是的,为了提高效率,我应该只从最后的位置运行find(),但我认为至少应该指出他的方向正确。我们都知道不成熟的优化是不好的--D – 2010-04-22 01:04:08

1
string replaceinString(std::string str, std::string tofind, std::string toreplace) 
{ 
     size_t position = 0; 
     for (position = str.find(tofind); position != std::string::npos; position = str.find(tofind,position)) 
     { 
       str.replace(position ,1, toreplace); 
     } 
     return(str); 
} 

使用它:

string replace = replaceinString(thisstring, " ", "%20"); 
string replace2 = replaceinString(thisstring, " ", "-"); 
string replace3 = replaceinString(thisstring, " ", "+");