C++ string字符串“1:2:41,1:3:5”怎么解析出1:2:41和1:3:5
时间: 2024-01-11 17:05:46 浏览: 32
可以使用C++中的字符串流stringstream来解析这个字符串,先将字符串以逗号为分隔符分割成两个子串,再将每个子串以冒号为分隔符分割成三个子串,即可得到所需的两个字符串。示例代码如下:
```
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
string str = "1:2:41,1:3:5";
stringstream ss(str);
string substr1, substr2;
getline(ss, substr1, ','); //以逗号为分隔符获取第一个子串
getline(ss, substr2); //获取第二个子串
cout << "substr1: " << substr1 << endl; //输出结果1:2:41
cout << "substr2: " << substr2 << endl; //输出结果1:3:5
return 0;
}
```
运行结果:
```
substr1: 1:2:41
substr2: 1:3:5
```
相关问题
C++ string字符串“1:2:41”怎么解析出1:2:41
可以使用stringstream将C string字符串"1:2:41"解析出1:2:41,具体代码如下:
```c++
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
char str[] = "1:2:41";
stringstream ss(str);
string token;
while (getline(ss, token, ':'))
{
cout << token << ":";
}
return 0;
}
```
输出结果为:
```1:2:41:```
其中,stringstream对象ss将C string字符串"1:2:41"转换为一个字符串流,然后使用getline函数按照":"作为分隔符,将字符串流中的字符分割成若干个子串,存储在字符串token中,最后将拆分出来的子串输出。
C++ string字符串“:,1:3:5”怎么解析出:和1:3:5
可以使用字符串的分割函数来解析出 ":" 和 "1:3:5",具体代码如下:
```cpp
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::string str = ":1:3:5";
std::vector<std::string> vec;
std::size_t prev = 0, pos;
while ((pos = str.find(':', prev)) != std::string::npos)
{
if (pos > prev)
vec.push_back(str.substr(prev, pos-prev));
prev = pos + 1;
}
if (prev < str.length())
vec.push_back(str.substr(prev));
// 输出结果
for (const auto& s : vec)
std::cout << s << " ";
std::cout << std::endl;
return 0;
}
```
输出结果为:
```
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_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)