C++没有自带的分割字符串函数
所以自己实现一个
分割要求:
输入:
1,24,569,78954,0,9,1,1111,230
输出这些数字
实现代码:
#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
using namespace std;
vector<string> splitString(string str,char split){ //分割字符串 返回字符串数组vector<string> res;string s = "";for (int i = 0; i < str.length();i++){if(str[i]==split){//遇到分隔符res.push_back(s);s = "";}else if(i==str.length()-1){//遇到结尾s += str[i];res.push_back(s);s = "";break;}else{s += str[i];}}return res;
}
int main(){string str;vector<int> res;cin >> str;vector<string> input = splitString(str,',');//确定分割符for (int i = 0; i < input.size();i++){//cout << input[i] << endl; //输出分割的字符串int x = stoi(input[i]); //字符串转化为十进制数字 头文件stringcout << x << endl;//输出数字}return 0;
}
输入:
1,24,569,78954,0,9,1,1111,230
输出:
1
24
569
78954
0
9
1
1111
230
拓展:
假如输入:
1:23,7:789,8:34,9:56,6:123,2:396
这是一组键值对,每对数用冒号分隔开,互相之间用逗号分割
要求输出对每对数排序后的结果,按照每对数字中的第一个从小到大排序
实现代码:
#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
using namespace std;
vector<string> splitString(string str,char split){ //分割字符串 返回字符串数组vector<string> res;string s = "";for (int i = 0; i < str.length();i++){if(str[i]==split){//遇到分隔符res.push_back(s);s = "";}else if(i==str.length()-1){//遇到结尾s += str[i];res.push_back(s);s = "";break;}else{s += str[i];}}return res;
}
struct mypair{int a;int b;
};
int main(){string str;cin >> str;vector<mypair> res;vector<string> input = splitString(str,',');for (int i = 0; i < input.size();i++){vector<string> p = splitString(input[i], ':');struct mypair x;x.a = stoi(p[0]);x.b = stoi(p[1]);res.push_back(x);}auto cmp = [](struct mypair x, struct mypair y){return x.a < y.a;};sort(res.begin(), res.end(), cmp);//排序for (auto i : res){cout << i.a << ":" << i.b << endl;}return 0;
}