替换C中字符串中的字符
Replacing a character from a string in C
我试过这种方法,但输出与输入相同。用户输入他想要替换的字符以及他想要替换的字母。我不明白我哪里错了。
#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;
}
问题是您在此代码段中使用的不是赋值运算符而是比较运算符
if(s[i]==x)
{
s[i] == y;
}
写入
if(s[i]==x)
{
s[i] = y;
}
注意函数gets
不安全,C标准不再支持。而是使用函数 fgets
.
还有这个电话
fflush(stdin);
有未定义的行为。删除它。
并使用
scanf(" %c",&x);
^^^
scanf(" %c",&y);
^^^
而不是
scanf("%c",&x);
scanf(" ");
scanf("%c",&y);
我试过这种方法,但输出与输入相同。用户输入他想要替换的字符以及他想要替换的字母。我不明白我哪里错了。
#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;
}
问题是您在此代码段中使用的不是赋值运算符而是比较运算符
if(s[i]==x)
{
s[i] == y;
}
写入
if(s[i]==x)
{
s[i] = y;
}
注意函数gets
不安全,C标准不再支持。而是使用函数 fgets
.
还有这个电话
fflush(stdin);
有未定义的行为。删除它。
并使用
scanf(" %c",&x);
^^^
scanf(" %c",&y);
^^^
而不是
scanf("%c",&x);
scanf(" ");
scanf("%c",&y);