string的empty,size,length等比较

怎甘沉沦 提交于 2020-02-23 10:49:44
 1 #include<iostream>
 2 #include<string>
 3 
 4 using namespace std;
 5 
 6 void Display(const string& str)
 7 {
 8     cout<<"String: "<<str<<endl;
 9     cout<<"Empty: "<<str.empty()<<endl;
10     cout<<"Size: "<<str.size()<<endl;
11     cout<<"Length: "<<str.length()<<endl;
12     cout<<"Capacity: "<<str.capacity()<<endl;
13     cout<<"Maxsize: "<<str.max_size()<<endl;
14     cout<<endl;
15 }
16 
17 
18 int _tmain(int argc, _TCHAR* argv[])
19 {
20     string s1="";  //无字节
21     Display(s1);
22 
23     string s2="  ";  //两个空子节
24     Display(s2);
25 
26     string s3="123456";
27     Display(s3);
28 
29     string s4="123 456 asd";
30     Display(s4);
31 
32    /* s3.resize(23);
33     Display(s3);*/
34 
35     system("pause");
36     return 0;
37 }

结果截图

但成员函数empty()用来检验字符数是否为0,亦即字符串是否为空时比length()或size()来得快。

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!