在此程序中,我们将看到如何在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
#include
#include
using namespace std;
main() {
string my_str = "ABC,XYZ,Hello,World,25,C++";
vector 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
cout <
}
}
输出结果ABC
XYZ
Hello
World
25
C++