C++ string字符串“1:2:41,1:3:5”怎么解析出1 2 41和1 3 5
时间: 2023-06-02 21:03:20 浏览: 60
可以使用C++的字符串分割(split)函数来实现字符串解析。首先将字符串按照逗号分隔,分别得到"1:2:41"和"1:3:5"两个字符串。然后再分别对这两个字符串进行再次分割,按照冒号分隔,最终得到1、2、41和1、3、5这两组数字。以下是代码实现:
```
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
int main()
{
std::string str = "1:2:41,1:3:5";
// 按逗号分隔
std::vector<std::string> strs;
std::stringstream ss(str);
std::string item;
while (std::getline(ss, item, ','))
{
strs.push_back(item);
}
// 按冒号分隔
std::vector<int> nums1;
std::vector<int> nums2;
for (auto&& s : strs)
{
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, ':'))
{
int num = std::stoi(item);
if (s == strs[0])
{
nums1.push_back(num);
}
else
{
nums2.push_back(num);
}
}
}
// 输出结果
for (auto&& n : nums1)
{
std::cout << n << " ";
}
std::cout << std::endl;
for (auto&& n : nums2)
{
std::cout << n << " ";
}
std::cout << std::endl;
return 0;
}
```
输出结果:
```
1 2 41
1 3 5
```
相关推荐
![hpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)