Search code examples
creplacecharc-stringsfunction-definition

Replacing a character from a string in C


I tried with this method but the output remains the same as the input. The user enters the character he wants to replace and with which letter he wants to replace with. I don't understand where did I go wrong.

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

Solution

  • The problem is that instead of the assignment operator you are using the comparison operator in this code snippet

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

    Write

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

    Pay attention to that the function gets is unsafe and is not supported by the C Standard any more. Instead use the function fgets.

    Also this call

    fflush(stdin);
    

    has undefined behavior. Remove it.

    And use

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

    instead of

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