Write programs to realize the string functions such as strlen, strcat, strcmp, substr by pointer.
int str_len(const char *str)
{
int len;
for(len=0; *str!='\0'; *str++) len++;
return len;
}
这个写法不知道为什么是错的(返回值和strcmp不一样):
int str_cmp(const char* s1, const char* s2)
{
while(*s1 == *s2 && s1 != '\0'){
s1++;
s2++;
}
return *s1 - *s2;
}
这样就对了:
int str_cmp(const char* str1,const char* str2)
{
while (*str1 && *str2 && (*str1 == *str2)){
str1 ++;
str2 ++;
}
return *str1 - *str2;
}
char *str_cat(char *s1, const char *s2)
{
int i=0,j=0;
while(s1[i] != '\0') i++;//得到s1的长度
while(s2[j] != '\0') s1[i++] = s2[j++];//s1末尾以后接上s2开头
s1[i] = '\0';//添加结束符号
return s1;
}
char *sub_str(char*str,char *subStr)
{
while (*str!='\0') {//扫描母串
char *p = str;
char *q = subStr;
char *res =NULL;
if (*p == *q) {//当两个字符串有一位相等时
res = p;//返回值指向这个指针
while (*q !='\0' && *p == *q){
p++;
q++;
}
if (*q =='\0')//到达子串的结尾
return res;
}
str++;
}
}