【问题标题】:Replacing a character from a string in C从C中的字符串替换字符
【发布时间】:2021-04-24 23:00:41
【问题描述】:

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

#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;
}

【问题讨论】:

  • 必填:Never use gets()
  • "%c" --> " %c"
  • 将双精度改为单精度:s[i]=y
  • 谢谢我应该使用 fgets() 而不是在这里获取吗?
  • 是的,使用fgets()。请注意,它会将\n 留在结果字符串中,而gets() 不会。

标签: c replace char c-strings function-definition


【解决方案1】:

问题在于,在这段代码 sn-p 中,您使用的是比较运算符而不是赋值运算符

    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);

【讨论】:

    猜你喜欢
    • 2011-10-20
    • 2014-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-09
    • 2019-01-24
    • 2012-08-30
    • 1970-01-01
    相关资源
    最近更新 更多