检查单词是否出现在句子中
句子是出现在字符串中的一组单词。在此问题陈述中,我们需要设置一个特定的单词并检查该单词是否出现在给定的字符串中。在 C++ 中,我们有一些预定义函数,例如 find()、npos() 和 istringstream(),它们将用于检查句子中是否存在单词。
使用标准库函数
该程序使用标准库函数,允许程序员使用 C 编译器的现有函数(例如 find() 和 npos())来执行某些任务。
语法
示例中使用了以下语法-
find()
find() 是 C++ 中的预定义函数,可帮助搜索给定输入中的元素。
npos()
npos() 是一个静态成员常量,它显示类型元素的最高值size_t。这仅表示在字符串中的子字符串中未找到匹配项。
算法
以下步骤为-
步骤 1:我们将通过提及所需的头文件(例如 iostream 和 string)来启动程序。
步骤 2:然后使用接受两个参数(类型为 const string& 的 s 和 w)的递归函数从给定的字符串变量(句子和单词)中获取值。
步骤 3:然后创建用于标准库函数的 size_t 类型的变量 found,并将该值存储为内置函数 find(),该函数搜索给定句子中存在的特定单词。
步骤 4:接下来,使用 if 语句通过使用 npos 和 != 运算符来设置条件,以检查给定的单词是否存在。如果找到单词,则返回 true,否则返回 false。
步骤 5:现在启动程序的主函数并创建两个字符串变量 - 句子和单词,用于程序的运行。
步骤 6:继续在 if 语句的条件中使用调用函数来检查单词是否在给定的句子中可用并返回结果。
示例
在下面的例子中,我们将使用两个变量分别设置句子和单词的值。然后它将使用一些条件和操作来检查单词是否存在于句子中。
#include <iostream> #include <string> using namespace std; bool word_checker(const string& s, const string& w) { // Find the index of the word in the sentences size_t found = s.find(w); // Check if the word is found if (found != string::npos) return true; return false; } // Start the main function int main() { string sentence = "The bestseller book"; string word = "book"; // Check whether the given word present in the sentence if (word_checker(sentence, word)) cout << "The given word is present in the sentence." << endl; else cout << "The given word is not present in the sentence." << endl; return 0; }
输出
The given word is present in the sentence.
使用 istringstream 对象
程序使用 istringstream 对象检查给定的单词是否存在于句子中。
语法
示例中使用了以下语法-
istringstream
istringstream 是一个预先存在的对象,它将输入流类操作为字符串。此类包含一系列字符。
算法
以下步骤是-
步骤 1:通过提及一些头文件(例如 iostream、string 和 sstream)来启动程序。头文件 sstream 启用字符串对象的内部操作。
步骤 2:然后程序使用递归函数 str_word_checker(),该函数接受两个参数 - 句子和单词,类型为 const string&,从给定的输入字符串变量接收值。
步骤 3:然后它将使用名为 istringstream check_sentence() 的预先存在的对象,该对象接受句子作为参数以启用内部操作。
步骤 4:接下来,初始化将在 while 循环中使用的字符串类型的变量 t。使用此循环通过提及右移位运算符即 >> 来设置条件,该运算符按空格迭代句子中的每个单词。
步骤 5:在 while 循环中,它将 if 语句中的等价条件设置为是否在句子中找到给定的单词。如果找到单词,则返回 true,否则返回 false。
步骤 6:现在启动主函数来设置两个字符串变量(例如 s 和 w)的输入,以通过函数调用传递值。
步骤 7:使用 if-else 语句,将条件设置为名为 str_word_checker() 的调用函数,以检查给定的单词是否在句子中可用。
示例
在下面的示例中,程序使用递归函数,该函数在需要时调用自身。然后使用简单的 while 循环,根据句子中存在的单词设置条件和操作并生成输出。
#include <iostream> #include <string> #include <sstream> using namespace std; bool str_word_checker(const string& sentence, const string& word) { istringstream check_sentence(sentence); string t; // 使用 >> 运算符按空格分隔句子 while (check_sentence >> t) { // 检查特定单词是否匹配 if (t == word) return true; } return false; } // 启动主函数 int main() { string s = "Welcome to C++ Tutorials"; string with = "C++"; // 检查单词是否存在于给定的列表中。 if (str_word_checker(s, w)) cout << "The given is word present in the string." << std::endl; else cout << "The given word is not present in the string." << std::endl; return 0; }
输出
The given word is not present in the string.
结论
此程序将句子指定为字符串,并将单词设置为特定变量,该变量确定其是否存在于给定的字符串中。我们使用两种方法来解决问题陈述,其中我们探索了各种内置函数,例如 find()、npos() 和 istringstream()。与此程序相关的应用程序很少,例如聊天机器人过滤器、单词搜索游戏、文本分析等。