下面的代码有什么问题?

问题描述:

问题是用“%20”替换字符串中包含的空格。所以基本上需要在有空间的地方插入字符串。因此,我想用%20替换所有空格,但只有部分字符串正在被替换。我可以看到在替换功能下面的代码有什么问题?

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

int spaces(char* s,int size) /*calculate number of spaces*/ 
{ 
    int nspace=0; 
    for(int i=0;i<size;i++) 
    { 
     if(s[i]==' ') 
     { 
      nspace++; 
     } 
    } 
    return nspace; 
} 

int len_new_string(char* inp,int l) /*calculate the length of the new string*/ 
{ 
    int new_length=l+spaces(inp,l)*2; 
    return new_length; 
} 

char* replace(char* s,int length) /*function to replace the spaces within a string*/ 
{ 
    int len=len_new_string(s,length); 
    char new_string[len]; 
    int j=0; 
    for(int i=0;i<length;i++) 
    { 
     if(s[i]==' ')  /*code to insert %20 if space is found*/ 
     { 
     new_string[j]='%'; 
     new_string[j+1]='2'; 
     new_string[j+2]='0'; 
     j=j+3; 
     } 
     else /*copy the original string if no space*/ 
     { 
     new_string[j]=s[i]; 
     j++; 
     } 
    } 
cout<<"Replaced String: "<<new_string<<endl; 
return s=new_string; 
} 


int main() 
{ 
    char str[]="abc def ghi "; 
    int length=sizeof(str)/sizeof(str[0]); 
    cout<<"String is: "<<str<<endl; 
    char *new_str=replace(str,length); 
    cout<<"Replaced String is: "<<new_str<<endl; 
} 
+2

_寻求调试帮助的问题(“为什么这个代码不工作?”)必须包含所需的行为,特定的问题或错误以及在问题本身中重现问题所需的最短代码。没有明确问题陈述的问题对其他读者无益。请参阅:如何创建[MCVE] ._ –

+0

您正在返回一个指向本地数组的指针。当你试图显示'new_string'时,它已经消失了。 –

的字符数组应该走出去的范围和发布正确的O/P。你没有得到段错误的唯一原因是显然没有其他程序在那个位置保留了内存。为了避免这种情况,请尝试使用具有填充一个字符数组,引用或指针将其移交和地方加油吧:(!记得delete[]它之后,再)

void replace(char *in, char *out, size_t length) 
{ 
    /* copy as-is for non-spaces, insert replacement for spaces */ 
} 

int main() 
{ 
    char str[]="abc def ghi"; 
    size_t buflen(strlen(str)+2*spaces(str, strlen(str))); 
    char output[buflen+1]; 
    memset(output, 0, buflen+1); 
    replace(str, output, strlen(str)); 
} 

另一种选择是new[]返回数组或者,我认为你出于某种原因而忽略了,一直使用std::string以避免数组问题。

+1

_“你没有得到段错误的唯一原因是显然没有其他程序在那个位置保留了内存。”_不,原因是未定义的行为,任何事情都可能发生。 –

+0

非常感谢。它正在工作。 – Vallabh