字符串长度与strlen、sizeof以及string的length和size

本文探讨了C/C++中strlen函数和sizeof运算符的区别,通过示例说明了它们如何计算字符串长度,强调了strlen不包含终止符'',而sizeof则包含。同时介绍了strcpy与strncpy的行为差异。

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

strlen函数是不包括‘\0’的长度的,sizeof计算的结果才包括'\0'的长度:
char str[] = "This is a test string two";
cout<<"str sizeof is :"<<sizeof(str)<<endl;
cout<<"str strlen is :"<<strlen(str)<<endl;

output:
str sizeof is:26

str strlen is:25

 

eg:

#include <iostream>
#include <string>
#include <string.h>

using namespace std;

int main()
{
    string str("hello");
    cout << "str length is " << str.length() << endl;
    cout << "str size is " << str.size() << endl;

    char buff[10];

    strncpy(buff, str.data(), str.length());
    // string是对象,无需靠'\0'结束
    buff[str.size()] = '\0'; // must has end code, because it's will undefine
    cout << "buff is [" << buff << "]" << endl;
    return 0;
}

output:

注:

1. strcpy  会自动补'0',strncpy 不会自动补'0'

关于字符串结束符可参见: 

C语言中字符串结束符'\0'的讨论

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值