字符串的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类型的字符串。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值