在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 训练狗狗基础
2 怎么训练狗狗笑
3 怎么训练狗狗卧下
4 上海狗狗训练基地
5 训练狗狗排便
6 狗狗基础训练
8 如何训练狗狗装死
9 狗狗站姿训练
10 狗狗训练用品
11 训练狗狗吧
12 狗狗要怎么训练
13 怎么训练狗狗玩球
14 训练狗狗唤回
15 狗狗训练躺下
16 狗狗训练指令
17 狗狗的训练技巧
18 狗狗不好训练