strlen与sizeof区别

本文通过两个示例详细对比了C++中strlen与sizeof的不同应用场景,解释了如何使用这两种函数来获取字符串长度和数组大小,并展示了string类对象的处理方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

例1:

#include<iostream>
#include<string.h>//strlen()的头文件
using namespace std;
int main()
{
   char s[5];
   strcpy(s,"cat");
   cout<<strlen(s)<<" "<<sizeof(s)<<endl;
    system("pause");
}
结果是 3 5。

strlen判断s中字符串的长度 为 3
sizeof判断s数组的大小 为 5

例2:

#include<iostream>
#include<string>
using namespace std;
int main()
{
  char *s="hello";
  char s1[]="hello";
  string a="hello";
  cout<<"sizeof(s): "<<sizeof(s)<<endl;//s指针的大小 
  cout<<"sizeof(a): "<<sizeof(a)<<endl; //string类对象的大小,类似于sizeof(char) 
  cout<<"strlen(s): "<<strlen(s)<<endl;//字符串长度 
  cout<<"strlen(s1): "<<strlen(s1)<<endl;//字符串长度 
  cout<<"sizeof(s1)/sizeof(char): "<<sizeof(s1)/sizeof(char)<<endl;//字符数组长度,是字符串长度+1. 
  cout<<"sizeof(s1):"<<sizeof(s1)<<endl;//sizeof(数组名),得到的是数组大小。
  cout<<"a.length():f "<<a.length()<<endl;//string型字符串长度 
  system("pause");
  return 0;
} 


评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值