运用strlen\strcpy\strcat\strcmp时需添加#include <string.h>头文件
size_t strlen(const char *s);
功能:计算字符串长度,不包括'\0'
char *strcpy(char *dest, const char *src);
功能:把src拷贝到dest
char *strcat(char *dest, const char *src);
功能:把字符串src追加到dest的后面
int strcmp(const char *s1, const char *s2);
功能:比较两个字符串大小,按字典序(在前为小)比较,出结果立即返回,后面不再比较
s1 > s2 正数 s1 < s2 负数 s1 == s2 0
重写strlen函数 (命名为str_len)
size_t str_len(const char *s)
{
assert(NULL != s);
const char* p = s;
while(*p); p++;
return p-s;
}
重写strcpy函数 (命名为str_cpy)
char *str_cpy(char *dest, const char *src)
{
assert(NULL != dest && NULL != src);
char* p = dest;
while(*p++ = *src++);
return dest;
}
重写strcat函数 (命名为str_cat)
char *str_cat(char *dest, const char *src)
{
assert(NULL != dest && NULL != src);
char* p = dest;
while(*p) p++;
while(*p++ = *src++);
return dest;
}
重写strcmp函数 (命名为str_cmp)
int str_cmp(const char *s1, const char *s2)
{
assert(NULL != s1 && NULL != s2);
while(*s1 && *s1 == *s2)
{
s1++;
s2++;
}
return *s1-*s2;
}
以上函数测试代码
#include <stdio.h>
#include <string.h>
#include <assert.h>
int main(int argc,cont char* argv[])
{
char str[256]
printf("str_len:%d\n",str_len(str));
printf("str_cpy:%s\n",str_cpy(str,"abc"));
printf("str_cat:%s\n",str_cat(str,"def"));
printf("str_cmp:%d\n",str_cmp("abc","aaa"));
}
assert:运用assert时需添加#include <assert.h>头文件
用于检测错误,表达式结果为0,则为假,并打印错误信息