20240212作业

本文详细介绍了如何使用C语言中的指针实现strlen、strcpy、strcat、strcmp等字符串处理函数,以及如何编写一个swap函数用于交换两个整数的值。
摘要由CSDN通过智能技术生成

用指针实现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;

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值