在C ++中解析以逗号分隔的std :: string
在此程序中,我们将看到如何在C++中解析逗号分隔的字符串。我们将在出现一些文本的地方放置一个字符串,并用逗号分隔。执行此程序后,它将把这些字符串拆分为向量类型的对象。
为了分割它们,我们使用getline()函数。该函数的基本语法如下:
getline (input_stream, string, delim)
此函数用于从输入流中读取字符串或行。
Input: Some strings "ABC,XYZ,Hello,World,25,C++" Output: Separated string ABC XYZ Hello World 25 C++
算法
Step 1: Create stream from given string Step 2: While the stream is not completed Step 2.1: Take item before comma Step 2.2: Add item into a vector Step 3: Return the vector
范例程式码
#include<iostream>
#include<vector>
#include<sstream>
using namespace std;
main() {
string my_str = "ABC,XYZ,Hello,World,25,C++";
vector<string> result;
stringstream s_stream(my_str); //create string stream from the string
while(s_stream.good()) {
string substr;
getline(s_stream, substr, ','); //get first string delimited by comma
result.push_back(substr);
}
for(int i = 0; i<result.size(); i++) { //print all splitted strings
cout << result.at(i) << endl;
}
}输出结果
ABC XYZ Hello World 25 C++
热门推荐
1 训练狗狗工作
4 狗狗定点排便训练
5 狗狗训练吠叫
6 狗狗尿垫训练
7 狗狗训练座
8 狗狗训练攻略
9 狗狗训练记
10 做训练狗狗
11 狗狗训练词
12 狗狗谢谢怎么训练
13 狗狗训练如厕
14 狗狗太凶怎么训练
15 狗狗训练它
16 狗狗克制训练
17 训练基地狗狗
18 怎么样训练狗狗大小硬