C语言 strchr 函数用法
class="content_article_viewer_show">
[[IMG_PLACEHOLDER_0]]
C语言中strchr函数作用是为在一个串中查找给定字符的第一个匹配之处,该函的原型为“char *strchr(const char *str, int c)”,使用时向str传入要被检索的字符串,c传入要搜索的字符即可。
演示实例
#include <stdio.h> #include <string.h> int main () { const char str[] = "http://www.runoob.com"; const char ch = '.'; char *ret; ret = strchr(str, ch); printf("|%c| 之后的字符串是 - |%s|\n", ch, ret); return(0); }
编译后运行结果:
|.| 之后的字符串是 - |.runoob.com|
使用示例
//#define FIRST_DEMO #define SECOND_DEMO #ifdef FIRST_DEMO #include <stdio.h> #include <conio.h> #include <string.h> #pragma warning (disable:4996) int main(void) { char string[17]; char *ptr; char c='T'; strcpy(string,"This is a string"); ptr=strchr(string,c); if (ptr) { printf("The character %c is at position:%d\n",c,ptr-string); } else { printf("The character was not found\n"); } getch(); return 0; } #elif defined SECOND_DEMO #include <stdio.h> #include <conio.h> #include <string.h> #pragma warning (disable:4996) int main(void) { char answer[100]; char *p; printf("Type something:\n"); fgets(answer,sizeof answer,stdin); if ((p=strchr(answer,'\n'))!=NULL) /*fgets不会像gets那样自动地去掉结尾的\n,所以程序中手动将\n位置处的值变为\0,代表输入的结束。*/ { *p='\0'; } printf("You typed \"%s\"\n",answer); getch(); return 0; } #endif
推荐教程:《C#》