求C风格字符串的长度

目录

1、使用sizeof计算字符串长度

2、使用strlenf计算字符串长度

3.C++中提供了string类,对于string类字符串,使用size()函数计算字符串长度。

4.获得字符串中从第i位开始长度为l的字符字串。


reference:https://www.runoob.com/cplusplus/cpp-strings.html

一、C 风格的字符串起源于 C 语言,并在 C++ 中继续得到支持。字符串实际上是使用 null 字符 '\0' 终止的一维字符数组。

1、使用sizeof计算字符串长度

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
char s1[6] = {'h', 'e', 'l', 'l', 'o', '\0'};//注意:要使用单引号'',不要使用双引号""。
//char s1[] = {'h', 'e', 'l', 'l', 'o', '\0'};也行,结果长度也为6。
char s2[] = "hello";
int len_s1 = sizeof(s1)/sizeof(s1[0]);
int len_s2 = sizeof(s2)/sizeof(s2[0]);
cout <<"s1:"<<s1<< "length of s1:"<<len_s1<<endl;
cout <<"s2:"<<s2<<"length of s1:"<<len_s2<<endl;
return 0;
}
/*
s1:hello length of s1:6
s2:hello length of s1:6

Process returned 0 (0x0)   execution time : 0.360 s
Press any key to continue.
*/

2、使用strlenf计算字符串长度

#include <iostream>
#include <cstring>
using namespace std;
int main()
{

char s1[] = {'h', 'e', 'l', 'l', 'o', '\0'};//写成char s1[6] = {'h', 'e', 'l', 'l', 'o', '\0'},结果还一样。
char s2[] = "hello";
int len_s1 = strlen(s1);
int len_s2 = strlen(s2);
cout <<"s1:"<<s1<< "length of s1:"<<len_s1<<endl;
cout <<"s2:"<<s2<<"length of s1:"<<len_s2<<endl;
return 0;

}

/*
s1:hello length of s1:5
s2:hello length of s1:5

Process returned 0 (0x0)   execution time : 0.276 s
Press any key to continue.*/

注意:不能用size()函数计算C风格字符串长度。

3.C++中提供了string类,对于string类字符串,使用size()函数和length()函数计算字符串长度。

#include <iostream>
#include <string>
using namespace std;

int main()
{

string s1 = "hello";
int len_s1 = s1.size();//不可用strlen()函数计算其长度;
int len_s1_1 = sizeof(s1)/sizeof(s1[0]);//有点奇怪啊。。。。。
cout <<"s1:"<<s1<<" "<< "length of s1:"<<len_s1<<endl;
cout <<"s1:"<<s1<<" "<< "length of s1:"<<len_s1_1<<endl;
return 0;

}
/* 
s1:hello length of s1:5
s1:hello length of s1:4

Process returned 0 (0x0)   execution time : 0.029 s
Press any key to continue.
*/

4.获得字符串中从第i位开始长度为l的字符字串。

#include <iostream>
#include <cstring>
#include <unordered_map>
using namespace std;

int main()
{
string str1("abcbcg");
int str1_length = str1.size();
cout <<str1_length<<endl;
cout <<str1<<endl;
cout <<str1.substr(1,5)<<endl;
return 0;
}
/*
6
abcbcg
bcbcg

Process returned 0 (0x0)   execution time : 0.118 s
Press any key to continue.
*/

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值