2016-09-05 18 views
0

文字列と文字を受け取る関数を作成する必要があります。この関数は、文字列内の文字のすべての出現を取り除き、削除された文字の総数を返します。私は不要な文字を削除できるように文字列を変更することができましたが、古い文字列を新しい文字列で置き換えることができないようです。事前にお返事ありがとうございます。文字列から不要な文字を削除する関数

int clearstr(char *st,char u){ 
    int i,j=0,total=0,size=strlen(st); 
    char *new_str=calloc(size,sizeof(char)); 
    for(i=0;i<size;i++){ 
     if(st[i]!=u){ 
      new_str[j]=st[i]; 
      j++;} 
     else total++; 
    } 
    new_str[j]='\0'; 
    printf("%s",new_str); 

    //until here all is good ,new_str has the modified array that i want but i can't find a way to replace the string in st with the new string in new_str and send it back to the calling function (main),thanks for any help // 

    return total; 
} 
+0

new_str [j] = '\ 0'; st [i] = '(new_str + i);} st [i] =' \ 0 '; for(i = 0; i insideNinja

答えて

0

あなたは新しい文字列を作成していますが、まだそれを使用していない。

は、これは私がこれまで管理してきたものです。内容をコピーするには、memcpyまたはstrcpyのような機能を使用できます。また、callocコールのメモリの割り当てを解除しないでください。これによりメモリリークが発生します。次のように試してください:

... 
new_str[j]='\0'; 
printf("%s",new_str); 

strcpy(st, new_str); // Copy the contents of the new string to the original one 
free(new_str); // Clear the memory of the allocation in this function, otherwise you get a memory leak 

return total; 
... 
+0

おかげで多くのことが私が探していたが、私はそれが私の人生のために働くように管理することができませんでした:D – insideNinja

関連する問題