2016-07-08 9 views
-4

質問は文字列に含まれるスペースを "%20"で置き換えることです。したがって、スペースがある場合はいつでも、文字列に挿入する必要があります。したがって、すべてのスペースを%20に置き換えたいのですが、部分文字列のみが置き換えられます。置換機能で正しいo/pを見ることができます以下のコードの問題点は何ですか?

#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

文字配列は範囲外になり、解放されます。あなたがsegfaultを取得しない唯一の理由は、他のプログラムがまだその場所にメモリを予約していないことは明らかです。これを避けるために、参照またはポインタでそれを手渡すと場所でそれを埋め、パディングとchar型の配列を使用してみてください:(!そして、その後delete[]にそれを覚えている)

は別のオプションが new[]にある
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)); 
} 

リターン・アレイはまたは私があなたが何らかの理由で放棄したと思うものは、アレイの問題を避けるために、すべてstd::stringを使用してください。

+1

_ "あなたがsegfaultを取得しない唯一の理由は、他のプログラムがまだその場所にメモリを予約していないということです。" - いいえ、理由は未定義の動作です。 –

+0

ありがとうございました。それは今働いている。 – Vallabh

関連する問題