字符串的sizeof和strlen

[code=c][/code]
#include <string>
#include <iostream>
using namespace std;

void main(){
    char user_name[] = { 'a', 's', '\n','\0' };//数组初始化的时候可以赋值        
    cout << "user_name " << strlen(user_name) << endl;//3  strlen是寻找从指定地址开始,到出现的第一个0之间的字符个数,他是在运行阶段执行的
    cout << "user_name " << sizeof(user_name) << endl;//4

    char a = 'wer';
    char b[ ] = "qwe";
    char c[5] = "qwe";
    //cout << "a " << strlen(a) << endl;//strlen 的参数是一个const char*类型的,和a数据类型不符,所以错误
    cout << "a " << sizeof(a) << endl;//1 char类型的大小
    cout << "b " << strlen(b) << endl;//3
    cout << "b " << sizeof(b) << endl;//4
    cout << "c " << strlen(c) << endl;//3
    cout << "c " << sizeof(c) << endl;//5

string user_name2="asdf";
    cout << user_name2.size() << endl;//4
    //cout << strlen(user_name2) << endl;//错误 不存在从实体类型std::string到const char类型的转换
    cout << sizeof(user_name2) << endl;//28,并不是字符串的长度,而是string类的大小


       [img=https://forum.csdn.net/PointForum/ui/scripts/csdn/Plugin/001/face/79.gif][/img]trlen是寻找从指定地址开始,到出现的第一个0之间的字符个数,他是在运行阶段执行的,而sizeof是得到数据的大小,在这里是得到字符串的容量。所以对同一个对象而言,sizeof的值是恒定的。string是C++类型的字符串,他是一个类,所以sizeof(s)表示的并不是字符串的长度,而是类string的大小。strlen(s)根本就是错误的,因为strlen的参数是一个字符指针,如果想用strlen得到s字符串的长度,应该使用sizeof(s.c_str()),因为string的成员函数c_str()返回的是字符串的首地址。实际上,string类提供了自己的成员函数来得到字符串的容量和长度,分别是Capacity()和Length()。string封装了常用了字符串操作,所以在C++开发过程中,最好使用string代替C类型的字符串。

猜你喜欢

转载自blog.csdn.net/hwxyyf/article/details/83041734