Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在C中替换字符串中的字符_C_Replace_Char_C Strings_Function Definition - Fatal编程技术网

在C中替换字符串中的字符

在C中替换字符串中的字符,c,replace,char,c-strings,function-definition,C,Replace,Char,C Strings,Function Definition,我尝试使用此方法,但输出与输入保持相同。用户输入要替换的字符以及要替换的字母。我不明白我哪里出错了 #include<stdio.h> char* replaceChar(char *s, char x,char y) { int i=0; while(s[i]) { if(s[i]==x) { s[i]==y; } i++; } return s;

我尝试使用此方法,但输出与输入保持相同。用户输入要替换的字符以及要替换的字母。我不明白我哪里出错了

#include<stdio.h>

char* replaceChar(char *s, char x,char y)
{
    int i=0;
    while(s[i])
    {
        if(s[i]==x)
        {
            s[i]==y;
        }
        i++;
    }

    return s;

}

int main()
{
    char string[30];

    printf("Enter the string:\n");
    gets(string);
    fflush(stdin);
    char x;
    char y;
    printf("Enter the character you want to replace:\n");
    scanf("%c",&x);
    printf("Enter the character you want to replace with:\n");
    scanf(" ");
    scanf("%c",&y);

    printf("After replacing the string :\n");
    printf("%s",replaceChar(&string[0],x,y));


    return 0;
}
#包括
char*replaceChar(char*s,char x,char y)
{
int i=0;
而(s[i])
{
如果(s[i]==x)
{
s[i]==y;
}
i++;
}
返回s;
}
int main()
{
字符串[30];
printf(“输入字符串:\n”);
获取(字符串);
fflush(stdin);
字符x;
chary;
printf(“输入要替换的字符:\n”);
scanf(“%c”、&x);
printf(“输入要替换为的字符:\n”);
scanf(“”);
scanf(“%c”、&y);
printf(“替换字符串后:\n”);
printf(“%s”,replaceChar(&string[0],x,y));
返回0;
}

问题在于,在此代码段中使用的不是赋值运算符,而是比较运算符

    if(s[i]==x)
    {
        s[i] == y;
    }

请注意,
get
函数是不安全的,C标准不再支持它。而是使用函数
fgets

还有这个电话

fflush(stdin);
具有未定义的行为。移除它

和使用

scanf(" %c",&x);
      ^^^

scanf(" %c",&y);
      ^^^ 
而不是

scanf("%c",&x);
scanf(" ");
scanf("%c",&y);

强制性:
%c”
-->
%c”
将double等于single:s[i]=yThanks我应该使用fgets()而不是get here吗?是的,使用
fgets()。请注意,它会将
\n
保留在结果字符串中,而
get()
不会。非常感谢它的工作!
scanf("%c",&x);
scanf(" ");
scanf("%c",&y);