1.查找子字符串在其他字符串中出现的次数
#include <stdio.h>
int countSubStr(char* str,char* s)
{
char* s1;
char* s2;
int count = 0;
while(*str!= '\0')
{
s1 = str;
s2 = s;
while(*s2 == *s1&&(*s2!='\0')&&(*s1!='\0'))
{
s2++;
s1++;
}
if(*s2 == '\0')
count++;
str++;
}
return count;
}
int main(int argc, const char * argv[]) {
char *c1 = "abcabcaabbccabc";
char *c2 = "abc";
printf("%d\n",countSubStr(c1, c2));
return 0;
}
2. strcpy的实现
#include <stdio.h>
char *strcpy(char *des, const char *source)
{
char* target = des;
while ((*des++ = *source++));
return target ;
}
int main(int argc, const char * argv[]) {
char c1[3];
const char *c2 = "aaa";
printf("%s\n",strcpy(c1, c2));
printf("%s\n",c1);
return 0;
}
3.strcmp的实现
/**
* 比较字符串的大小
*/
int sCmp(char* l,char* r)
{
assert(l!=0&&r!=0);
while(*l == *r &&*l != '\0') l++,r++;
if(*l > *r)
return 1;
else if(*l == *r)
return 0;
return -1;
}
int main(int argc, const char * argv[]) {
char *c1 = "abcabcaabbccabc";
char *c2 = "abc";
printf("%d\n",sCmp(c1, c2));
return 0;
}