//1.计数器的写法
//2.递归的写法
//3.指针-指针
#include <assert.h>
int my_strlen(const char* str)
{
int count = 0;
assert(str != NULL);
while (*str != '\0')
{
count++;
str++;
}
return count;
}
int main()
{
int len = my_strlen("abcdef");//6
//错误写入
//char arr[] = { 'a','b','c','d','e','f' };//19,寻找\0,但是这种写入方式没有\0,只能是随机找,随机停止
//int len = strlen(arr);
printf("%d\n", len);
return 0;
}
#include <stdio.h>
#include <assert.h>
#include <string.h>
char* my_strcpy(char* dest, const char* src)
{
assert(dest != NULL);
assert(src != NULL);
char* ret = dest;
while (*src != '\0')//可以直接精简成这样while(*dest++ = *src++)
{
*dest = *src;
dest++;
src++;
}
*dest = *src;
return ret;//返回目的空间的起始地址
}
int main()
{
char arr1[] = { "abcdef" };
char arr2[] = { "bit" };
my_strcpy(arr1, arr2);
printf("%s\n", arr1);
return 0;
}
char *arr1 = "abcdefhi",不是字符串数组,是一个常量字符串,无法修改
int main()
{
char arr1[30] = { "Hello" };
char arr2[] = { "World" };
strcat(arr1, arr2);
printf("%s\n", arr1);
return 0;
}
#include <stdio.h>
#include <assert.h>
#include <string.h>
char* my_strcat(char* dest,const char* src)
{
char* ret = dest;
assert(dest != NULL);
assert(src != NULL);
//找到目的字符串的'\0'
while (*dest != '\0')
{
dest++;
}
while (*dest++ = *src++)
{
;
}
return ret;
}
int main()
{
char arr1[30] = { "Hello" };
char arr2[] = { "World" };
my_strcat(arr1, arr2);
printf("%s\n", arr1);
return 0;
}
int main()
{
char* p1 = "tbcdefhig";
char* p2 = "sqwer";
int ret = strcmp(p1, p2);
printf("%d\n", ret);
return 0;
}
#include <stdio.h>
#include <assert.h>
#include <string.h>
int my_strcmp(const char* str1,const char* str2)
{
assert(str1 && str2);
while (*str1 == *str2)
{
if (*str1 == '\0')
{
return 0;//相等
}
str1++;
str2++;
}
if (*str1 > *str2)
{
return 1;//大于
}
else
return -1;//小于
}
int main()
{
char* p1 = "abcdef";
char* p2 = "abcwer";
int ret = my_strcmp(p1, p2);
printf("%d\n", ret);
return 0;
}
int main()
{
char arr1[10] = { "abcdef" };
char arr2[] = { "helloworld" };
strncpy(arr1, arr2, 6);
printf("%s\n", arr1);
return 0;
}