原文链接:https://blog.csdn.net/Wan_shibugong/article/details/81949513
求字符串的长度 :strlen
长度不受限制的字符串函数 :strcpy;strcat; strcmp
长度受限制的字符串函数 :strncpy ;strncat ;strncmp
字符串查找 :strchr ;strrchr ;strpbrk ;strstr
求字符串的长度strlen
#include <stdio.h>
#include <assert.h>
int my_strlen(const char *str) //const在这里修饰是一大亮点 因为strlen函数只需计算字符串的长度,
{ //无需更改,所以加上const修饰,不能随意改变
int count = 0;
assert(str != NULL); // assert()在这里是第二亮点,断言的作用,判断指针是否为空指针
while(*str != '\0')
{
count++;
str++;
}
return count;
}
int main()
{
char *p = "abcdef";
int ch = my_strlen(p);
printf("%d\n",ch);
return 0;
}
长度不受限制的字符串strcpy、strcat、strcmp
#include <stdio.h>
#include <assert.h>
#include <windows.h>
char * my_strcpy(char * str_des, const char * str_source)
{
assert(str_des);
assert(str_source);
char * ret = str_des;
while (*ret++ = *str_source++)
{
;
}
return str_des;
}
int main()
{
char str1[] = "hello world";
char str2[20] = { 0 }; //将空间全部初始化为0
char *str3 = my_strcpy(str2, str1);
printf("%s\n", str2);
printf("%s\n", str3);
system("pause");
return 0;
}
#include <stdio.h>
#include <assert.h>
#include <windows.h>
char * my_strcat(char * str_source, char * str_des)
{
assert(str_des);
assert(str_source);
char *p = str_source;
while (*p) //不能写成*p++当p开始为0还会++
{
p++;
}
while (*p++ = *str_des++);
return str_des;
}
int main()
{
char str[40] = { 0 };
my_strcat(str,"hello ");
printf("%s\n",str);
my_strcat(str,"world!");
printf("%s\n", str);
system("pause");
return 0;
}
#include <stdio.h>
#include <assert.h>
#include <windows.h>
//strcmp字符串比较
//两个字符串相等返回0,第一个大于第二个返回正数,反之负数
int my_strcmp(const char* str1, const char * str2)
{
while (*str1 && *str2)
{
if (*str1 == *str2)
{
str1++;
str2++;
}
else if (*str1 > *str2)
return 1;
else
return -1;
}
if (*str1)
return 1;
if (*str2)
return -1;
return 0;
}
int main()
{
char str1[] = "a";
char str2[] = "b";
int n = my_strcmp(str1, str2);
printf("%d\n", n);
system("pause");
return 0;
}