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?
fflush(stdin)andgets()...both are bad.chararray. Arrays incdon't automatically resize. Even if you were correctly replacing the charactercwith the strings, ifsis more than one character long it's going to overwrite characters inps,, that's not what you want. You can certainly move characters around in the array to make room for the new ones, but that's going to be more difficult coding-wise than simply writing to a new array.&s->sinscanf("%s", &s)*ptr = s;. It's actually an error.