用指针实现strlen、strcpy、strcat、strcmp,写一个swap函数实现两数交换
以下是使用 C 语言实现上述函数的示例代码:
1.strlen
函数:计算字符串的长度
size_t strlen(const char *str)
{
size_t length = 0;
while (*str != '\0')
{
length++;
str++;
}
return length;
}
2.strcpy
函数:复制字符串
char *strcpy(char *destination, const char *source)
{
char *destination_start = destination;
while ((*destination++ = *source++) != '\0');
return destination_start;
}
3.strcat
函数:连接字符串
char *strcat(char *destination, const char *source)
{
char *destination_start = destination;
while (*destination != '\0')
{
destination++;
}
while ((*destination++ = *source++) != '\0');
return destination_start;
}
4.strcmp
函数:比较字符串
int strcmp(const char *str1, const char *str2)
{
while (*str1 == *str2 && *str1 != '\0' && *str2 != '\0')
{
str1++;
str2++;
}
return *(const unsigned char *)str1 - *(const unsigned char *)str2;
}
5.swap
函数:交换两个数
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}