在我的代码中找不到从字符串中删除字符的错误

时间:2015-04-16 12:30:30

标签: c string

#include <stdio.h>
#include <stdlib.h>


void squeeze(char s[], int c);

int main(){

    int i, max = 200,c;
    char s[max];

    for(i=0; i <max-1 && (c=getchar())!=EOF; ++i){
        s[i] =c;
    }
    squeeze(s, c);

    printf("%s", s);

}
void squeeze (char s[], int c){

    int i, j;
    for(i=j=0; s[i] != '\0'; i++){
        if(s[i] != c){
            s[j++] = s[i];
        }   
    }
    s[j] = '\0';
}

上述代码应该从输入字符串中删除所有出现的字符c。代码正在编译而没有任何错误,但在运行代码时,即使它包含字符c,它也会打印相同的输入字符串。我无法弄清楚我在哪里出错了。

3 个答案:

答案 0 :(得分:3)

在调用s之前,您永远不会终止squeeze(),因此它不是有效的字符串。因此,此代码具有未定义的行为。

然后这个:

squeeze(s, c);

应该是

squeeze(s, 'c'); 

如果您要删除字符'c'。现在您传递变量c,其值为EOF;没有意义。

答案 1 :(得分:2)

主要变化如

...
printf("Input string : ");
fgets(s, sizeof s, stdin);
printf("Enter you want to delete characters : ");
c = getchar();

squeeze(s, c);
...

答案 2 :(得分:1)

如果我理解正确您试图删除squeeze中读取的所有最后一个字符,除其他外,它失败了因为您将null-terminator s[i]作为{ {1}}到c。那永远不会奏效。一些修订,它现在删除所有出现的最后一个char读取:

squeeze

<强>输出

#include <stdio.h>

void squeeze(char *s, int c);

int main(){

    int i = 0, max = 200, c = 0;
    char s[max];

    while ((c = getchar()) != EOF && c != '\n' && i < max-1)
        s[i++] = c;
    s[i] = 0;

    if (i > 0)
        squeeze (s, s[i-1]);

    printf("\n  %s\n\n", s);

    return 0;
}

void squeeze (char *s, int c) {

    int i = 0, j = 0;
    while (s[i]) {
        if(s[i] != c){
            s[j++] = s[i];
        }
        i++;
    }
    s[j] = 0;
}