前言
C++Primer 读书笔记,一个小白的自留地,欢迎大佬批评指正~
3.1 命名空间的using声明
#include3.2 标准库类型string// using std::cin; // using std::cout; // using std::endl; using namespace std; //这个更好 int main() { int i; cin >> i; cout << i << endl; return 0; }
3.2.1 定义和初始化string对象
#includeusing namespace std; int main() { string s1; //空字符串 string s2 = s1; string s3 = "hiya"; string s5("Hiya"); string s4(10, 'c'); //cccccccccc return 0; }
直接初始化和拷贝初始化
3.2.2 string对象上的操作
读写string对象
读取未知数量的string对象
#includeusing namespace std; int main() { string s; int i = 0; while (cin >> s){ cout << "Line " << ++i << " : " << s << endl; } return 0; }
使用getline读取一整行
#includeusing namespace std; int main() { string s; while (getline(cin, s)) { cout << s << endl; } return 0; }
string 的 empty 和 size 操作
#includeusing namespace std; int main() { string s; int i = 0; while (getline(cin, s)) { if (!s.empty()) cout << "Line " << ++i << " : " << s << "[" << s.size() << "]" << endl; } return 0; }
string::size_type 类型
#includeusing namespace std; int main() { string s("hello world"); int n = -10; auto len = s.size(); cout << len << endl; cout << (n < len) << endl; return 0; }
比较 string 对象
#includeusing namespace std; int main() { string str = "Hello"; string phrase = "Hello World"; string slang = "Hiya"; cout << (str < phrase) << endl; cout << (slang > str) << endl; return 0; }
两个 string 对象相加
字面值和 string 对象相加
应该把s2往前放
3.2.3 处理 string 对象中的字符
处理每个字符?使用基于范围的for语句
#includeusing namespace std; int main() { string s("some thing"); for (auto c : s) cout << c << endl; return 0; }
#include#include using namespace std; int main() { string s = "Hello world!!!"; decltype(s.size()) punct_cnt = 0; //不进行函数运算,但会判断s.size的返回类型,punct_cnt的类型和s.size的返回类型一样 for (auto c : s) { //对于s中的每个字符 if (ispunct(c)) //如果该字符是标点符号 ++punct_cnt; //将标点符号的计数值加1 } cout << punct_cnt << " punctuation characters in " << s << endl; return 0; }
使用范围for语句改变字符串中的字符
#include#include using namespace std; int main() { string str = "Hello world!!!"; for (auto &c : str) { //这里的引用跟引用的定义存在冲突,理论上引用与对象绑定以后就不能再变了 //可能的解释就是这种循环里和常规的for不一样,每次都做的是初始化而不是赋值 c = toupper(c); //c是一个引用,因此将改变s中字符的值 cout << c; } cout << endl; cout << str << endl; return 0; }
只处理一部分字符
使用下标执行随机访问
总结:
直接初始化和拷贝初始化
string::size_type 类型
使用范围for语句改变字符串中的字符



