在 C++ 中對字串進行標記化
在本節中,我們將瞭解如何在 C++ 中對字串進行標記化。在 C 語言中,我們可以對字元陣列使用 strtok() 函式。這裡我們有一個 string 類。現在,我們來看看如何使用該字串中的某個分割符來分割字串。
要使用 C++ 特性,我們必須將字串轉換為字串流。然後,我們可以使用 getline() 函式來完成此任務。getline() 函式使用字串流、需要傳送輸出的另一個字串和停止掃描流的分隔符。
讓我們看以下示例,瞭解該函式如何工作。
示例程式碼
#include <iostream>
#include <vector>
#include <sstream>
using namespace std;
int main() {
string my_string = "Hello,World,India,Earth,London";
stringstream ss(my_string); //convert my_string into string stream
vector<string> tokens;
string temp_str;
while(getline(ss, temp_str, ',')){ //use comma as delim for cutting string
tokens.push_back(temp_str);
}
for(int i = 0; i < tokens.size(); i++) {
cout << tokens[i] << endl;
}
}輸出
Hello World India Earth London
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP