strchr函数功能为在一个串中查找给定字符的第一个匹配之处
#include<stdio.h>
#include<string.h>
int main() {
char str[] = "This is a sample string";
char* pch;
printf("looking for the 's' character in \"%s\"...\n",str);
pch = strchr(str,'s');
while (pch !=NULL)
{
printf("found at %d\n",pch -str +1);
pch = strchr(pch+1,'s');
}
return 0;
}
strchr自己实现的内部原理
#include<stdio.h>
#include<string.h>
//内部实现原理
char* StrChr(const char *str,int n) {
while (*str) {
if (*str==n) {
return str;
}
str++;
}
return NULL;
}
int main() {
char str[] = "This is a sample string";
char* pch;
printf("looking for the 's' character in \"%s\"...\n",str);
pch = StrChr(str,'s');
while (pch != NULL) {
printf("found at %d\n",pch-str+1);
pch = StrChr(pch+1,'s');
}
return 0;
}