读入有空格的字符串
1、getline
1 2 3
| #include <string> string str; getline(cin,str);
|
2、将句子中每个单词读入队列中
1 2 3 4 5 6 7 8 9 10 11
| string w; stringstream cina(sentence1); stringstream cinb(sentence2);
while(cina >> w) { q1.emplace_back(w); } while(cinb >> w) { q2.emplace_back(w); }
|
读入有空格的字符数组
1 2
| char str[10000] cin.getline(str,10000);
|
字符拼接到字符串
1 2 3
| string s = ""; char c; s += c;
|
字符的运算和转化
1)字符-‘0’就转化成数字。
1 2 3 4
| "11:23" => hour:11, minute:23 int getMin(string s) { return (int(s[0] - '0') * 10 + int(s[1] - '0')) * 60 + int(s[3] - '0') * 10 + int(s[4] - '0'); }
|
2)数字+’0’转化成字符
1 2 3
| char a='3',b='1'; a = a -'0' + '1'; a = (a - '0') % 2 + '0';
|
3) 字符-‘a’变数字
1 2 3 4
| int arr[26] = {0}; for(char c : s) { arr[c - 'a']++; }
|
整型/浮点型转字符串
①string to_string(int n);
②stringstream
1 2 3 4 5 6 7 8 9 10 11 12
| #include <sstream> #include <string> #include <iostream> string convet(int i){ stringstream ss; string str; ss<<i; ss>>str; return str; }
|
substr(int index, int num) 从下标index开始,取num个数
1 2 3 4 5 6
| string s1 ="abcdefgh"; cout << s1.substr(3,4) <<endl;
|
查找字符串数组中每个字符串的每一个字符。
vector<string>words={"hello","leecode","code"};
1 2 3 4 5
| for(string word : words){ for(char ch : word){ ... } }
|
处理含有空格的字符串
1.通过字符拼接为字符串
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| string s; getline(cin,s); vector<string>str; vector<int> vec; string tmp = ""; for(int i = 0; i< s.size(); i++){ if(s[i] != ' '){ tmp += s[i]; }
else{ str.push_back(tmp); tmp = ""; } } str.push_back(tmp);
|
初始化字符串