2016-07-08 104 views
-4

問題是用「%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'時,它已經消失了。 –

回答

1

的字符數組應該走出去的範圍和發佈正確的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