Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
C program to replace all occurrence of a character in a string
In C programming, replacing characters in a string is a common string manipulation task. This involves searching for a specific character and replacing it with another character either for all occurrences or just the first occurrence.
Syntax
for(i = 0; string[i] != '\0'; i++) {
if(string[i] == old_char) {
string[i] = new_char;
}
}
Method 1: Replace All Occurrences
This method replaces every occurrence of a character in the string −
#include <stdio.h>
#include <string.h>
int main() {
char string[100], ch1, ch2;
int i;
printf("Enter a string: ");
fgets(string, sizeof(string), stdin);
string[strcspn(string, "<br>")] = '\0'; /* Remove newline */
printf("Enter character to search: ");
scanf("%c", &ch1);
getchar(); /* Clear buffer */
printf("Enter replacement character: ");
scanf("%c", &ch2);
for(i = 0; string[i] != '\0'; i++) {
if(string[i] == ch1) {
string[i] = ch2;
}
}
printf("String after replacing '%c' with '%c': %s<br>", ch1, ch2, string);
return 0;
}
Enter a string: Tutorials Point Enter character to search: i Enter replacement character: % String after replacing 'i' with '%': Tutor%als Po%nt
Method 2: Replace First Occurrence Only
This method replaces only the first occurrence of a character and stops −
#include <stdio.h>
#include <string.h>
int main() {
char string[100], ch1, ch2;
int i;
printf("Enter a string: ");
fgets(string, sizeof(string), stdin);
string[strcspn(string, "<br>")] = '\0'; /* Remove newline */
printf("Enter character to search: ");
scanf("%c", &ch1);
getchar(); /* Clear buffer */
printf("Enter replacement character: ");
scanf("%c", &ch2);
for(i = 0; string[i] != '\0'; i++) {
if(string[i] == ch1) {
string[i] = ch2;
break; /* Stop after first replacement */
}
}
printf("String after replacing first '%c' with '%c': %s<br>", ch1, ch2, string);
return 0;
}
Enter a string: Tutorial Point Enter character to search: o Enter replacement character: # String after replacing first 'o' with '#': Tut#rial Point
Key Points
- Use
fgets()instead ofgets()for safer string input - Remove newline character from
fgets()input usingstrcspn() - Use
getchar()to clear input buffer afterscanf() - The
breakstatement in Method 2 stops after the first replacement
Conclusion
Character replacement in strings can be done efficiently using simple loops. Choose Method 1 for replacing all occurrences or Method 2 for replacing only the first occurrence based on your requirements.
Advertisements
