How to print a specified character in a string in the C language?
In C language, loops and conditional statements can be used to iterate through a string and print specific characters based on certain conditions.
Here is an example code demonstrating how to print a specified character in a string.
#include <stdio.h>
void printCharInString(const char* str, char target) {
int i = 0;
while (str[i] != '\0') {
if (str[i] == target) {
printf("%c", target);
} else {
printf(" ");
}
i++;
}
}
int main() {
const char* str = "Hello, World!";
char target = 'o';
printCharInString(str, target);
return 0;
}
The function printCharInString in the example code above is used to print a specified character in a string. It loops through each character in the string using a while loop and if the current character matches the target character, it prints the target character, otherwise it prints a space. The main function shows how to call the printCharInString function, and pass in the string and target character.
When running the above program, all occurrences of the target character ‘o’ will be displayed, with all other characters replaced by spaces. The output will be:
o o