Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4710584
  • 博文数量: 930
  • 博客积分: 12070
  • 博客等级: 上将
  • 技术积分: 11448
  • 用 户 组: 普通用户
  • 注册时间: 2008-08-15 16:57
文章分类

全部博文(930)

文章存档

2011年(60)

2010年(220)

2009年(371)

2008年(279)

分类: C/C++

2008-11-17 21:34:42

zj@zj:~/C_parm/string/own_str/strchr$ cat strchr.c
/**
 * The strchr() function returns a pointer to the first occurrence of the
 * character c in the string s.
 * The strchr() and strrchr() functions return a pointer to the matched
 * character or NULL if the character is not found.
 * strchr.c
*/

 
#include<stdio.h>
#include<stdlib.h>

char* my_strchr(const char* s, int c);
char* my_strrchr(const char* s,int c);

int main()
{
   char* str = "1a,2a,3a,4a!";
   char c = 'a';
   printf("the first occurrence \'%c\' of %s is\n%s\n",c,str,my_strchr(str,c));
   printf("the last occurrence \'%c\' of %s is\n%s\n",c,str,my_strrchr(str,c));
   
  exit(EXIT_SUCCESS);
}

char* my_strchr(const char *s, int c)
{
   int i = 0;
   while((*(s+i)!=c)&&(*(s+i)!='\0'))
    i++;
   if(*(s+i)==c)
    return (s+i);
   else
    return NULL;
}

char* my_strrchr(const char* s,int c)
{
    char* last;
    last = my_strchr(s,c);
         while(my_strchr(last+1,c))
          {
     last=my_strchr(last+1,c);    
          }    
    return last;
}
zj@zj:~/C_parm/string/own_str/strchr$ ./strchr
the first occurrence 'a' of 1a,2a,3a,4a! is
a,2a,3a,4a!
the last occurrence 'a' of 1a,2a,3a,4a! is
a!

阅读(3642) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~