例子:
1:
string s1, s2;
cin >> s1 >> s2;
cout << s1 << s2 << endl;
这段代码是输入两个字符串,然后再输出,输入完hello后碰到空格,cin就直接跳过去并把值赋值给s1,然后返回cin类型,接着是world,赋值给s2。
2:
string world;
while (cin >> world) {
cout << world << endl;
}
这段代码指的是我们输入的是hello world man,然后按回车;首先读取到的是hello然后输出然后是endl换行,此时又跳到while循环,看读取到的是否还是string类型,空格自动跳过。下一个是the,然后输出换行....直到输出结束。
3:
string s1="hello", s2="world";
string s3 = s1 + "m"; //对
string s4 = "hello" + "m"; //错
string s5 = s1 + "," + "world"; //对
string s6 = "hello" + "," + s2; //错
string s7 = "hello" + ("," + s2); //对
c++语言中,字符串字面值并不是string对象。
对于s3,加号两边一个是对象一个是字面值,是可以相加的;
对于s4,加号两边都是字面值,没有对象,是不能进行相加的;
对于s5,运用链式法则,第一个加号两边一个是对象一个是字面值,是可以相加的,然后返回一个临时的对象,则第二个加号满足相加条件;
对于s6,加了括号优先级变高,先算括号里面的,其余原理同上。
4:
string s("Hello World!!!");
//算一算有多少个标点符号
decltype(s.size()) punct_cnt = 0; //decltype(s.size())返回一个合适的类型,类似于(int punct_cnt = 0)
for (auto c : s) {
if (ispunct(c)) {
++punct_cnt;
}
}
cout << punct_cnt << "个标点符号在" << s << endl;
//转换为大小写
string orig = s;
for (auto& c : s) { //这里是引用,相当于给s中的每个字符贴上c的标签
c = toupper(c); //c只是s[0]的别名,用完返回给c是一样的
}
cout << s << endl;
s = orig;