在 C++ 中解析逗號分隔的 std::string


在這個教程中,我們將學習如何在 C++ 中解析逗號分隔的字串。我們將輸入一個包含一些文字的字串,並且這些文字以逗號分隔。本教程執行後,我們將會把這些字串拆分為一個 vector 型別物件。

為了拆分這些字串,我們將使用 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++

更新於:2015-08-25

7K+ 瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

點選開始
廣告