How to replace specific characters in a C language string?
In C language, loops and conditional statements can be used to replace specified characters in a string. Here is an example code:
#include <stdio.h>
void replaceChar(char *str, char oldChar, char newChar) {
int i = 0;
while (str[i] != '\0') {
if (str[i] == oldChar) {
str[i] = newChar;
}
i++;
}
}
int main() {
char str[] = "Hello, World!";
char oldChar = 'o';
char newChar = 'x';
printf("原始字符串: %s\n", str);
replaceChar(str, oldChar, newChar);
printf("替换后字符串: %s\n", str);
return 0;
}
The running result is:
原始字符串: Hello, World!
替换后字符串: Hellx, Wxrld!
In the example above, the replaceChar function takes a pointer to a string, a character to be replaced called oldChar, and a character to replace it with called newChar. It loops through each character in the string and replaces any instances of oldChar with newChar.