目录
1. Locate first occurrence of character in string
1. Locate first occurrence of character in string
#include <string.h>
char * strchr ( const char * str, int character );
Returns a pointer to the first occurrence of character in the C string str.
The terminating null-character is considered part of the C string. Therefore, it can also be located in order to retrieve a pointer to the end of a string.
上述内容是 cplusplus 对 strchr 函数的介绍,
可以看出 strchr 函数返回要查找字符第一次出现的位置,如果没有查找成功,则返回空指针。
2. 源代码
#include <stdio.h>
#include <assert.h>
#define SRC_STR "hello"
#define FIND_CHAR 'l'
char *Strchr(const char *src, int c) {
assert(NULL != src);
while (('\0' != *src) && (*src != (char)c))
++src;
if ((char)c == *src)
return (char *)src;
return NULL;
}
void test() {
char *ret = Strchr(SRC_STR, FIND_CHAR);
if (NULL != ret)
printf("call Strchr, find [%c/%s] in src: %s\n", FIND_CHAR, ret, SRC_STR);
else
printf("call Strchr, not find [%c/%s] in src: %s\n", FIND_CHAR, ret, SRC_STR);
}
int main(void) {
test();
return 0;
}
3. 输出结果
call Strchr, find [l/llo] in src: hello