自制函数实现strlen、strcpy、strcmp、strcat函数
程序员文章站
2022-06-05 19:59:21
...
C语言代码实现如下:
/*************************************************************************
> File Name: 1.c
> Author: Macro Red
> Mail: [email protected]
> Environment: Lunix Ubuntu 16.04 LTS
> Created Time: 2018-01-29 16:36
************************************************************************/
/* Standard includes. */
#include <stdio.h>
/* Library includes. */
/* User files */
int MyStrlen(char a[]);
int MyStrlen2(const char* s);
char *MyStrcpy(char a[], const char b[]);
int MyStrcmp(const char a[], const char b[]);
char *MyStrcat(char a[], const char b[]);
/**
* @brief main function
* @param None
* @retval None
*/
int main(void)
{
char ch1[20] = {0}, ch2[20] = "Hello";
printf("ch1:%s\tch2:%s\n", ch1, ch2);
printf("MyStrlen(ch1):%d,MyStrlen(ch2):%d\n", MyStrlen(ch1), MyStrlen(ch2));
printf("MyStrcmp(ch1,ch2):%d\n", MyStrcmp(ch1,ch2));
printf("MyStrcat(ch1,ch2):%s\n", MyStrcat(ch1,ch2));
printf("MyStrcpy(ch1,ch2):%s\n", MyStrcpy(ch1,ch2));
printf("ch1:%s\tch2:%s\n", ch1, ch2);
return 0;
}
/**
* @brief user "strlen"
* @param char a[]
* @retval int
*/
int MyStrlen(char a[])
{
int count = 0;
while(a[count++] != '\0');
return count-1;
}
/**
* @brief user "strlen2"
* @param char a[]
* @retval int
*/
int MyStrlen2(const char* s)
{
return (*s?(strlen(s + 1) + 1) : 0);
}
/**
* @brief user "strcpy"
* @param char a[], const char b[]
* @retval None
*/
char *MyStrcpy(char a[], const char b[])
{
int i;
for(i = 0; b[i] != '\0'; i++)
{
a[i] = b[i];
}
a[i] = '\0';
return a;
}
/**
* @brief user "strcmp"
* @param const char a[], const char b[]
* @retval int
*/
int MyStrcmp(const char a[], const char b[])
{
int i;
for(i = 0; a[i] != '\0' && b[i] != '\0'; i++)
{
if(a[i] < b[i])
return -1;
else if(a[i] > b[i])
return 1;
}
if(a[i] == '\0' && b[i] == '\0')
return 0;
else if(a[i] == '\0')
return -1;
else if(b[i] == '\0')
return 1;
return 0;
}
/**
* @brief user "strcat"
* @param char a[], const char b[]
* @retval None
*/
char *MyStrcat(char a[], const char b[])
{
int a_falg, i;
a_falg = MyStrlen(a);
for(i = 0; b[i] != '\0'; i++)
{
a[i+a_falg] = b[i];
}
a[i+a_falg] = '\0';
return a;
}