曲径通幽论坛

标题: strchr() -- 在一个字符串中查找第一个出现的字符 [打印本页]

作者: beyes    时间: 2011-1-22 18:52
标题: strchr() -- 在一个字符串中查找第一个出现的字符
原型
#include <string.h>
char *strchr (const char *s, int c);

说明
该函数用来从一个字符串中查找第一个出现的字符,如果字符串包含该字符则返回指向该字符的指针,否则返回NULL。


示例代码
#include <stdio.h>
#include <string.h>
int main()
{
         const char *s = "hello world";
         char *p = NULL;
         char c;
         printf ("input a char want to find: ");
         scanf ("%c", &c);
         if (!strchr(s, c)) {
                 printf ("Not found!\n");
                 return (1);
         }
         printf ("%c\n", *strchr(s, c));
         return (0);
}
运行输出
$ ./strchr
input a char want to find: o
o
$ ./strchr
input a char want to find: z
Not found!

供参考的函数实现代码
char * strchr(const char * s, int c)
{
  for(; *s != (char) c; ++s)
   if (*s == '\0')
    return NULL;
  return (char *) s;
}





欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2