初始化string 对象的方式
| string s1; | 默认构造函数 s1 为空串 |
|---|---|
| string s2(s1); | 将 s2 初始化为 s1 的一个副本 |
| string s3(“value”); | 将 s3 初始化为一个字符串字面值副本 |
| string s4(n, ‘c’); | 将 s4 初始化为字符 ‘c’ 的 n 个副本 |
• 读取并忽略开头所有的空白字符(如空格,换行符,制表符)。
• 读取字符直至再次遇到空白字符,读取终止。
1、读取一行
int main()
{
string s; // empty string
cin >> s; // read whitespace-separated string into s //输入hello world
cout << s << endl; // write s to the output //输出hello
return 0;
}
2、可以把多个读操作或多个写操作放在一起
string s1, s2; cin >> s1 >> s2; // read first input into s1, second into s2 //输入 hello world cout << s1 << s2 << endl; // write both strings //输出 helloworld
3、读入未知数目的string 对象
string 的输入操作符也会返回所读的数据流,因此,可以把输入操作作为判断条件
int main()
{
string word;
// read until end-of-file, writing each word to a new line
while (cin >> word)
cout << word << endl;
return 0;
}
4、使用getline 读取整行文本
getline 并不忽略行开头的换行符。只要 getline 遇到换行符,即便它是输入的第一个字符,getline 也将停止读入并返回
int main()
{
string line;
// read line at time until end-of-file
while (getline(cin, line))
cout << line << endl;
return 0;
}
string 对象的操作
| s.empty() | 如果 s 为空串,则返回 true,否则返回 false。 |
|---|---|
| s.size() | 返回 s 中字符的个数 |
| s[n] | 返回 s 中位置为 n 的字符,位置从 0 开始计数 |
| s1 + s2 | 把 s1 和s2 连接成一个新字符串,返回新生成的字符串 |
| s1 = s2 | 把 s1 内容替换为 s2 的副本 |
| v1 == v2 | 比较 v1 与 v2 的内容,相等则返回 true,否则返回 false |
| !=, <, <=, >, and >= | 保持这些操作符惯有的含义 |



