strchr
is a function in the C standard library used to find the first occurrence of a specified character in a string; this function is similar to the memchr
function, except that memchr
can be applied to any data type, whereas strchr
can only be applied to strings.
Reference
strchr Function Header File
The header file for the strchr
function is <string.h>
. Before using the strchr
function, make sure to include this header file in your C code:
#include <string.h>
strchr Function Prototype
char* strchr(const char* s, int c);
The strchr
function locates the first occurrence of the character c
(converted to char
) in the string pointed to by s
; the null terminator '\0'
is considered part of the string.
Parameters
s
: A pointer to the string to be searched;c
: The character to be found, which is converted tochar
type;
Return Value
The memchr
function returns a pointer to the located character; if c
is not found in the string, it returns a null pointer NULL
;
strchr Example Code
Checking if a string contains a space
If the string does not contain a space, strchr()
should return NULL
;
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
bool contains_space(const char* src) {
if (strchr(src, ' ') == NULL) {
return false;
}
return true;
}
int main() {
const char* str = "perfcode.com";
if (contains_space(str)) {
printf("the string contains a space.\n");
}
else {
printf("the string does not contain a space.\n");
}
return 0;
}