简易字符串分词
1.利用cin特性(不读取空格)
思路:
通过while循环 cin 输入的方式,输入单词伪装拆分字符串,通过getchar判断是否输入回车,碰到回车跳出循环
代码:
#include<bits/stdc++.h>
using namespace std;
string str;
int main() {
while (cin >> str) {
if(getchar(str) == '\n') break;
cout << str << endl;
}
}
缺点 :只能以空格分隔
2.利用字符串流拆分(默认)
原理和方法1类似
头文件:<sstream>
istringstream类 用于执行C++风格的串流的输入操作。
ostringstream类 用于执行C++风格的串流的输出操作。
stringstream类 同时支持C++风格的串流的输入输出操作。
代码:
#include<bits/stdc++.h>
using namespace std;
string s1, str;
int main() {
getline(cin, str);
stringstream rule(str); // 将str读入流中,这里用的构造
while(rule >> s1){ // 将流中内容,写入s1
cout << s1 << endl;
}
}
缺点:只能以空格分隔
3.stringstream提取int数据
代码:
#include<bits/stdc++.h>
using namespace std;
string nums;
int num;
int main() {
nums = "12 69 37 55a48";
stringstream rule(nums);
while(rule >> num){
cout << num << endl;
}
}
特点:遇到不符合类型就中断,无视空格读入, 写出去的就没有了。
4.c++ 实现 split
vector<string> split(string str, char del) {
stringstream ss(str);
string temp;
vector<string> ret;
while (getline(ss, temp, del)) {
ret.push_back(temp);
}
return ret;
}
int main()
{
string str_cin("one#two#three");
vector<string> res= split(str_cin, '#');
for (auto c : res)
cout << c << endl;
return 0;
}