Home:ALL Converter>Not able to replace a character in a string with another string

Not able to replace a character in a string with another string

Ask Time:2017-09-01T22:54:37         Author:akash11

Json Formatter

Here's a question where we need to replace all occurences of a character in a string with another new string. Given below is the question:

Write a program that replaces the occurence of a given character (say c) in a primary string (say PS) with another string (say s).

Input: The first line contains the primary string (PS) The next line contains a character (c) The next line contains a string (s)

Output: Print the string PS with every occurence of c replaced by s.

NOTE: - There are no whitespaces in PS or s. - Maximum length of PS is 100. - Maximum length of s is 10.

Below is my code:

#include<stdio.h>
int main()
{
    char ps[100],*ptr,c,s[10];

    printf("Enter any string:");
    gets(ps);

    printf("Enter the character you want to replace:");
    scanf("%c",&c);

    printf("Enter the new string:");
    fflush(stdin);
    scanf("%s",&s);

    ptr=ps;

    while(*ptr!='\0')
    {
        if(*ptr==c)
        *ptr=s;
        ptr++;
    }

    printf("Final string is:");
    puts(ps);
    return 0;
}

I am not able to replace a character with a string. It just gives me a garbage output in place of the character that I want to replace.

But, when I declare it as a character, the output is as expected. It replaces the character with another character.

Could you please help me with this?

Author:akash11,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/46002942/not-able-to-replace-a-character-in-a-string-with-another-string
Scott Hunter :

In C, a string is a sequence of characters, represented by the address of the first. So *ptr = s should have gotten you a warning about mismatched types from the compiler. If you want to insert a string into another, you'll need to move the other characters around to make room for it.\n\nBut your problem description does not seem to require that you make a new string, just print as if you had. So you could loop through the original string, and for each character, if it is to be replaced, print the replacement string, otherwise print the original character.",
2017-09-01T14:58:23
yy