c++字符串系列之strlen函数

180it 2020-10-09 AM 2400℃ 0条

常用字符串处理函数有以下几种:strlen strncpy strcpy strncat strcat strncmp strcmp strstr。
这里首先介绍strlen函数。

1.strlen(const cr *s)返回的是字符串的长度。获得的是有效字符的长度,不包括末尾的结束符'\0'。

strlen函数的原型是:

unsigned int strlen(const char *str)
{
    assert(str != Null);
    unsigned int len = 0;
    while (*str++)
    {
        len++;
    }
    return len;
}

2.与sizeof的区别

sizeof是一个运算符,表示求对象在内存中占用的字节数。对于字符串求sizeof,则字符串末尾的‘\0'也要计算在内,占一个字节。

sizeof运算符参数可以是任何对象。而strlen函数的参数必须是const char*类型。

3.例子分析,下面是用strlen和sizeof的代码分析

#include <iostream>
using namespace std;
 
int main()
{
    char str[] = "hello,world";
    char name[20] = "Jenny";
    char *ch = "hello";
    int len1 = strlen(str);
    int len2 = strlen(name);
    int len3 = strlen(ch);
    cout << "strlen:字符串长度 " << endl;
    cout << "str: " << len1 << endl;
    cout << "name: " << len2 << endl;
    cout << "ch: " << len3 << endl;
    cout << "sizeof: 内存字节数" << endl;
    cout << "str: " << sizeof(str) << endl;//这里对字符串末尾的\0是占用内存字节的,所以用sizeof求字节数比字符串长度大1.
    cout << "name: " << sizeof(name) << endl;
    cout << "ch: " << sizeof(ch) << endl;//因为ch是指针,指针是地址,是占用32位,也就是4个字节。与指针是何类型无关
 
    return 0;
}

输出结果为:
strlen:字符串长度
str: 11
name: 5
ch: 5
sizeof: 内存字节数
str: 12
name: 20
ch: 4
请按任意键继续. . .

支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

c++字符串系列之strlen函数