1、写出在母串中查找子串出现次数的代码.
int count1(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;
}
2、查找第一个匹配子串位置,如果返回的是s1长度len1表示没有找到
size_t find(char* s1,char* s2)
{
size_t i=0;
size_t len1 = strlen(s1)
size_t len2 = strlen(s2);
if(len1-len2<0) return len1;
for(;i<len1-len2;i++)
{
size_t m = i;
for(size_t j=0;j<len2;j++)
{
if(s1[m]!=s2[j])
break;
m++;
}
if(j==len2)
break;
}
return i<len1-len2?i:len1;
}
3、实现strcpy()函数
char *strcpy(char *destination, const char *source)
{
assert(destination!=NULL&&source!=NULL);
char* target = destinaton;
while(*destinaton++=*source++);
return target ;
}
4、strcmp函数
int strcmp(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;
}
5、实现字符串的反转
void reserve(char* str)
{
assert(str != NULL);
char * p1 = str;
char * p2 = str-1;
while(*++p2);
//一般要求不能使用 strlen
p2 -= 1;
while(p1<p2)
{
char c = *p1;
*p1++ = *p2;
*p2-- = c;
}
}
5、判断一个字符串是不是回文
int IsReverseStr(char *str)
{
int i,j;
int found=1;
if(str==NULL)
return -1;
char* p = str-1;//将p指针指向字符串末尾
while(*++p!= '\0');
--p;
while(*str==*p&&str<p) str++,p--;
if(str < p)
found = 0;
return found;
}
6、收索特定的字符
int search(char *cpSource, int n, char ch)
{
int i;
for(i=0; i<n && *(cpSource+i) != ch; ++i);
return i;
}