目录
3.C++中提供了string类,对于string类字符串,使用size()函数计算字符串长度。
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.
*/