check if string contains a character in c
Check if String Contains a Character in C
To check if a string contains a specific character in C, you can use the strchr
function from the C standard library. Here are the steps to do this:
- Include the Necessary Header File:
Include the
<string.h>
header file to use thestrchr
function.Use the
strchr
Function:- Call the
strchr
function with the string and the character you want to search for as its arguments. - If the function returns a non-NULL value, the character is present in the string; otherwise, it's not.
Here's an example of how you can use the strchr
function to check if a string contains a specific character:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
char ch = 'o';
if (strchr(str, ch) != NULL) {
printf("The character '%c' is present in the string.\n", ch);
} else {
printf("The character '%c' is not present in the string.\n", ch);
}
return 0;
}
In this example, the str
array contains the string "Hello, World!" and we want to check if it contains the character 'o'. The strchr
function is used to perform this check.