从给定的句子中找出以给定词为前缀的词
在处理自然语言处理或文本分析时,通常需要在较大的文本体中搜索特定的单词或短语。一个常见的任务是找到句子中以给定前缀开头的所有单词。在本文中,我们将探讨如何使用C++来完成这个任务。
算法
读取输入的句子和前缀。
将输入的句子分解为单个单词。
For each word in the sentence, check if it starts with the given prefix.
如果单词以该前缀开头,则将其添加到匹配的单词列表中。
打印匹配的单词列表。
Example
#include #include #include using namespace std; int main() { string sentence, prefix; vector words; // Read in the input sentence and prefix sentence="The quick brown fox jumps over the lazy dog"; prefix="fox"; // Tokenize the input sentence into individual words string word = ""; for (auto c : sentence) { if (c == ' ') { words.push_back(word); word = ""; } else { word += c; } } words.push_back(word); // Find all words in the sentence that start with the given prefix vector matches; for (auto w : words) { if (w.substr(0, prefix.length()) == prefix) { matches.push_back(w); } } // Print the list of matching words cout