string对象小结
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str1 = "hello"; //赋值初始化,不包括字面值常量最后的空字符
string str2 = "hello ";
string str3("hello"); //直接初始化,不包括字面值常量最后的空字符
string str4("hello ");
cout << str1.size() << '\t' << str2.size() << '\t' << str3.size() << '\t' << str4.size() << '\t' << endl;
//5,6,5,6 其中6表示字符串中的空格,并不是末尾的空字符
//string对象不可用strlen()函数计算字符数,strlen()函数仅针对于字符数组,string对象使用自带函数s.size()即可size函数的类型是string::size_type,不能与int混用
***//string对象在使用cin时从第一个非空白字符开始接收并到第一个空白字符截至,即不包括空白字符;但是cout可以输出空白字符
//getline()函数可以得到一整行,并且以换行符为结束***
string str5("hello world!!!");
decltype(str5.size()) count = 0;
for(auto c : str5)
{
if (ispunct(c))
count++;
}
//范围for循环必须使用引用才可改变每个元素的值
cout << "punctuation in str5 is:" << count << endl; //统计标点符号数:3
str5[5] = 's'; //string对象可使用下标访问每个元素并且能改变值
}
return 0;
}