1. 封装函数实现strlen功能
#include <stdio.h>
size_t MyStrlen(const char *pstr)
{
size_t cnt = 0;
while (*pstr++ != '\0')
{
++cnt;
}
return cnt;
}
int main(void)
{
char str[256] = {0};
size_t len = 0;
gets(str);
len = MyStrlen(str);
printf("数组长度为:%ld\n", len);
return 0;
}
2. 封装函数实现strcpy功能
#include <stdio.h>
char *MyStrcpy(char *str_1, const char *str_2)
{
char *str = str_1;
while (*str_2 != '\0')
{
*str_1 = *str_2;
str_1++;
str_2++;
}
*str_1 = '\0';
return str;
}
int main(void)
{
char str_1[30] = {0};
char str_2[30] = {0};
gets(str_2);
MyStrcpy(str_1, str_2);
puts(str_1);
return 0;
}
3. 封装函数实现strcat功能
#include <stdio.h>
char *MyStrcat(char *str_1, const char *str_2)
{
char *str = str_1;
while (*str_1++ != '\0');
--str_1;
while (*str_2 != '\0')
{
*str_1++ = *str_2++;
}
*str_1= '\0';
return str;
}
int main(void)
{
char str_1[30] = {"hello"};
char str_2[30] = {"world"};
MyStrcat(str_1, str_2);
puts(str_1);
return 0;
}
4. 封装函数实现strcmp功能
#include <stdio.h>
int MyStrcmp(char *str_1, char *str_2)
{
while (*str_1 == *str_2 && *str_1 != '\0')
{
str_1++;
str_2++;
}
return *str_1 - *str_2;
}
int main(void)
{
char str_1[30] = {0};
char str_2[30] = {0};
int num = 0;
gets(str_1);
gets(str_2);
num = MyStrcmp(str_1, str_2);
printf("num = %d\n", num);
return 0;
}