在 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++
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP