如何在 C++ 中使用定界符解析字串
本文將說明如何通過在 C++ 中指定分隔符來解析字串。
使用 find()
和 substr()
方法使用定界符來解析字串
本方法使用字串類的內建 find()
方法。它把一個要尋找的字元序列作為 string
型別,把起始位置作為一個整數引數。如果該方法找到了傳遞的字元,它返回第一個字元的位置。否則,它返回 npos
。我們將 find
語句放在 while
迴圈中,對字串進行迭代,直到找到最後一個定界符。為了提取定界符之間的子字串,使用 substr
函式,每次迭代時,將 token
推到 words
向量上。在迴圈的最後一步,我們使用 erase
方法刪除字串的處理部分。
#include <iostream>
#include <string>
#include <vector>
using std::cout; using std::cin;
using std::endl; using std::string;
using std::vector; using std::istringstream;
int main(){
string text = "He said. The challenge Hector heard with joy, "
"Then with his spear restrain'd the youth of Troy ";
string delim = " ";
vector<string> words{};
size_t pos = 0;
while ((pos = text.find(delim)) != string::npos) {
words.push_back(text.substr(0, pos));
text.erase(0, pos + delim.length());
}
for (const auto &w : words) {
cout << w << endl;
}
return EXIT_SUCCESS;
}
輸出:
He
said.
The
...
Troy
使用 stringstream
類和 getline
方法使用定界符來解析字串
在這個方法中,我們把 text
字串變數放到 stringstream
中,用 getline
方法對其進行操作。getline
提取字元,直到找到給定的 char
,並將標記儲存在 string
變數中。請注意,這個方法只能在需要單字元定界符的時候使用。
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using std::cout; using std::cin;
using std::endl; using std::string;
using std::vector; using std::stringstream;
int main(){
string text = "He said. The challenge Hector heard with joy, "
"Then with his spear restrain'd the youth of Troy ";
char del = ' ';
vector<string> words{};
stringstream sstream(text);
string word;
while (std::getline(sstream, word, del))
words.push_back(word);
for (const auto &str : words) {
cout << str << endl;
}
return EXIT_SUCCESS;
}
使用 copy
函式通過單個空格分隔符解析字串
copy
是一個 <algorithm>
庫函式,它可以遍歷指定的元素範圍,並將其複製到目標範圍。首先,我們用 text
引數初始化一個 istringstream
變數。之後,我們利用 istream_iterator
來迴圈處理以空格分隔的子字串,最後輸出到控制檯。但請注意,這個解決方案只有在 string
需要在白空格分隔符上進行分割時才有效。
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <iterator>
using std::cout; using std::cin;
using std::endl; using std::string;
using std::vector; using std::istringstream;
int main(){
string text = "He said. The challenge Hector heard with joy, "
"Then with his spear restrain'd the youth of Troy ";
istringstream iss(text);
copy(std::istream_iterator<string>(iss),
std::istream_iterator<string>(),
std::ostream_iterator<string>(cout, "\n"));
return EXIT_SUCCESS;
}
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn