相对于C语言中麻烦的C字符串操作,C++中提供了string类。本文将继续继承前文的风格,以代码为驱动,初步简介C++string类最简单的部分。
string的初始化
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1;
cin >> s1;//遇到回车或者空格停止
string s2(s1);//用字符串s1,初始化s2
string s3("value!");//另一种方法
string s4 = s3;//字符串的直接赋值
string s5(10, 'a');//把string对象初始化为10个a组成的串
cout << s1 << endl;
cout << s2 << endl;
cout << s3 << endl;
cout << s4 << endl;
cout << s5 << endl;
cout << s3.size() << endl;//打印s3中元素的个数
return 0;
}
作为一种复杂而庞大的编程语言C++中为很多特定情况下的特殊操作设定了特殊的重载函数,getline()便是其中之一
getline()有个奇怪的特性,即它会读入换行,但是紧接着它就会把它丢掉
#include <iostream>
#include <string>
using namespace std;
int main()
{
string line;
while (getline(cin, line))//getline会把空格读入,但是在将所存内容存到string对象时,会把换行丢掉
cout << line << endl;
string word;
getline(cin, word);
cout << word.empty() << endl;//检测是否为空,为空返回true
return 0;
}