分类: LINUX
2010-07-30 15:33: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!