字符串函数

1. char * strcat()

#include <stdio.h>
char * strcat(char * s1,const char * s2) {
char *p=s1;
while (*p)
p++;
while(*p++ = *s2++)
;
return s1;
}

2.size_t strlen(const char *s) {

    const char * p=s;

    while(*s)

            s++;

    return s-p;

            }

为何要编写strlen?

毕竟有sizeof运算符。

假设 char *str="hello";

理所当然的去尝试输出sizeof(str),发现输出的是4,原来sizeof(str)输出的是指针的大小

再次输出sizeof(*str),发现输出的是1,是sizeof(char)的值。

于是必须编写求字符串的大小的函数。

如果是 char str[]="hello",sizeof(str)输出的是6,正确输出字符串的内存大小

可以发现sizeof求的是内存大小。

3. char * strcmp( )

int strcmp (const char * s1,const char *s2) {
int i;
for(i=0;s1[i] == s2[i];++i)
    if(s1[i]=='\0')
    return 0;
return s1[i]-s2[i];
}

惯用法:

1.查找字符串末尾:

while (*p)
p++;

2.复制

while(*p++ = *s2++)

;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值