C++ string字符串“1:2:41,1:3:5”怎么解析出1:2:41和1:3:5
时间: 2024-01-11 18:05:36 浏览: 126
可以使用字符串分割的方法,将字符串按照 "," 分割成若干个子字符串,然后再将每个子字符串按照 ":" 分割成若干个子串,即可得到需要的结果。具体代码如下:
```
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
string str = "1:2:41,1:3:5";
vector<string> vec1;
vector<vector<string>> vec2;
// 分割字符串
int start = 0, end = 0;
while ((end = str.find(",", start)) != string::npos) {
vec1.push_back(str.substr(start, end - start));
start = end + 1;
}
vec1.push_back(str.substr(start));
// 再次分割子字符串
for (auto s : vec1) {
vector<string> v;
start = 0, end = 0;
while ((end = s.find(":", start)) != string::npos) {
v.push_back(s.substr(start, end - start));
start = end + 1;
}
v.push_back(s.substr(start));
vec2.push_back(v);
}
// 显示结果
for (auto v1 : vec2) {
for (auto v2 : v1) {
cout << v2 << ":";
}
cout << endl;
}
return 0;
}
```
输出结果为:
```
1:2:41:
1:3:5:
```
阅读全文