Introduction
In this post, you will learn how to replace a character in a given string using a C program. Replacing characters is a common task in string manipulation, and understanding this process is essential for beginner programmers working with character arrays in C.
C Program to Replace a Character in a Given String
#include <stdio.h>
int main() {
char str[100], oldChar, newChar;
int i;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
printf("Enter the character to replace: ");
scanf("%c", &oldChar);
getchar(); // consume newline character
printf("Enter the new character: ");
scanf("%c", &newChar);
for (i = 0; str[i] != '\0'; i++) {
if (str[i] == oldChar) {
str[i] = newChar;
}
}
printf("Updated string: %s", str);
return 0;
}
Explanation
fgets()
reads the entire input string including spaces.- The user provides the character to be replaced and the new character.
- The loop iterates through each character in the string and replaces it if it matches.
- The final updated string is displayed.
Sample Output
Enter a string: hello world
Enter the character to replace: l
Enter the new character: x
Updated string: hexxo worxd
Use Cases
- Replacing sensitive or special characters.
- Creating text formatters or filters.
- Enhancing understanding of string traversal in C.