【算法竞赛】拆分字符串方法总结

  • 方式1:使用stringstream拆分
#include<bits/stdc++.h>
using namespace std;
string nums;
int num;
int main() {
   nums = "12 69 37    55a48";
   stringstream ss(nums);
   while(ss >> num){
      cout << num << endl;
   }
}

输出:

12
69
37
55

缺点:如碰到数据类型不符的值,会中断输入;分隔符只能是空格

  • 方式2:
#include <bits/stdc++.h>
using namespace std;
string nums, num;
int main(){
    nums = "12 69 37    55a48";
    stringstream ss(nums);
    while (getline(ss, num, ' ')){
        cout << num << endl;
    }
}

输出:

12
69
37



55a48

缺点:只能转为字符串,但分隔符扩展到任意。后续可通过stoi()转int型、stod()转double型、stoll()转ll型、stoull转__int128_t等
tips:
int等转string也可通过该方法实现,另外也可通过to_string()实现.

附:C++读取文件并分词

ifstream ifs;
ifs.open(path, ios::in);
while (getline(ifs, num, ' ')){
	/* do something */
}
ifs.close();
posted @ 2024-04-03 13:01  yichen111  阅读(45)  评论(0)    收藏  举报