[英]using iterator to get phrases in a string.
我的向量包含很多句子,例如“你好,你好嗎”。 我希望能夠從一個句子中提取大小為2和5的短語,然后將其存儲在另一個向量中。 例如,從上面的字符串中,我希望獲得“ hello there”,“ hello there how”,“ hello there how are”和“ hello there how you”。
我試圖通過將句子拆分成單獨的單詞,然后使用以下命令將它們存儲在向量中:
while( getline(stream, word, ' ') )
{
vecWord.push_back(word);
}
這將刪除所有空白並存儲每個單詞。 我知道迭代器指向向量中的每個元素。 如何使用迭代器指向每個元素(又稱每個單詞)並將其組合為大小2-5
任何幫助,將不勝感激
嘗試這個。 給定all
,它是所有單詞的列表,而target
則是所需子字符串中的單詞列表。 這可以分解成過於獨立的問題。 首先,找到子字符串,然后找到包含它的以下所有子字符串。 第一部分實際上與如何在字符串中找到子字符串的一般問題相似。 即,如何在“ abc7845xyz”中找到“ 45x”。 如果要掌握迭代器的使用方式,那么我建議您查找使用常規C數組索引樣式迭代編寫的字符串搜索算法,然后嘗試將其轉換為迭代器。
for(auto i = all.begin();i < all.end() - target.size();i++){
auto temp_i = i;
bool found = found = true;
for(auto j = target.begin();found && j < target.end();j++, temp_i++)
found = *temp_i == *j;
// Substring found, so print all subsequent substrings containing it.
if(found){
auto start = i;
for(auto end = i + target.size();end < all.end();end++){
for(auto j = start;j <= end;j++)
cout << j << " ";
cout << endl;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.