[英]how do you split a string embedded in a delimiter in C++?
我了解如何通過 C++ 中的分隔符將字符串拆分為字符串,但是如何拆分嵌入在分隔符中的字符串,例如嘗試拆分”~.hello~. random junk... ~!world~!”
”~.hello~. random junk... ~!world~!”
通過字符串”~!”
到[“hello”, “ random junk...”, “world”]
的數組中? 是否有任何 C++ 標准庫函數,或者如果沒有任何算法可以實現這一點?
#include <iostream>
#include <vector>
using namespace std;
vector<string> split(string s,string delimiter){
vector<string> res;
s+=delimiter; //adding delimiter at end of string
string word;
int pos = s.find(delimiter);
while (pos != string::npos) {
word = s.substr(0, pos); // The Word that comes before the delimiter
res.push_back(word); // Push the Word to our Final vector
s.erase(0, pos + delimiter.length()); // Delete the Delimiter and repeat till end of String to find all words
pos = s.find(delimiter); // Update pos to hold position of next Delimiter in our String
}
res.push_back(s); //push the last word that comes after the delimiter
return res;
}
int main() {
string s="~!hello~!random junk... ~!world~!";
vector<string>words = split(s,"~!");
int n=words.size();
for(int i=0;i<n;i++)
std::cout<<words[i]<<std::endl;
return 0;
}
上面的程序將查找出現在您指定的分隔符之前、中間和之后的所有單詞。 通過對 function 進行細微更改,您可以使 function 滿足您的需要(例如,如果您不需要查找出現在第一個分隔符或最后一個分隔符之前的單詞)。
但是根據您的需要,給定的 function 根據您提供的分隔符以正確的方式進行分詞。
我希望這能解決你的問題!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.