檢查給定單詞是否出現在字串中


C++ 具有一個預定義函式 find(),它允許從第一個元素範圍搜尋到最後一個元素。 在本文中,我們將瞭解如何使用此 find() 函式來檢查給定單詞是否出現在字串中。

讓我們舉個例子。

給定的字串是“John and mark have same color of t-shirt”;

為了在字串中搜索單詞,我們將建立一個表示為搜尋查詢器的變數。 讓我們取兩個變數並檢查給定的單詞是否存在。

Var1 = peter; - 此單詞在字串中未找到。

Var2 = mark; − 此單詞在字串中找到。

因此,我們將根據模式匹配應用條件並使其滿足以在字串中找到給定的單詞。

在本文中,我們將解決給定單詞是否出現在字串中。

方法

find()

find() 是字串中一個預定義的方法,它有助於搜尋給定單詞是否出現在字串中。

string::npos

npos 表示無位置,如果它返回 true,則表示在任何位置都沒有發現匹配項。

演算法

  • 我們將從名為 ‘iostream’‘string’ 的標頭檔案開始。

  • 我們正在開始主函式並將字串值初始化為名為 ‘myString’ 的變數。 我們將從儲存在此變數中的字串中找到給定的單詞。

  • 我們將建立兩個變數,即 ‘word1’‘word2’。 我們將在這兩個單詞在 myString 變數中搜索。

  • 現在我們使用 if 語句來檢查給定的單詞是否出現在字串中。

    ‘myString.find( word1 ) != string::npos’

  • 接下來,帶有 ‘myString’ 變數的 find() 函式有助於搜尋給定的單詞,如果它不等於 string::npos,則它將返回語句,即給定單詞出現在字串中。 如果未找到該單詞,則它將返回語句,即給定單詞未出現在字串中。

示例

在此程式中,我們將解決給定單詞是否出現在字串中。

#include <iostream>
#include <string>
using namespace std;
int main() {
   string myString = "The quick grey monkey jumps over the lazy dog";
   string word1 = "grey";
   string word2 = "mouse";
   // check whether the given word present in string or not.
   if ( myString.find( word1 ) != string::npos ) {
      cout << word1 << " is present in the string." << endl;
   } else {
      cout << word1 << " is not present in the string." << endl;
   }
   // second time searching the word but process is same
   if ( myString.find( word2 ) != string::npos ) {
      cout << word2 << " is present in the string." << endl;
   } else {
      cout << word2 << " is not present in the string." << endl;
   }
   return 0;
}

輸出

grey is present in the string.
mouse is not present in the string.

結論

我們探討了給定單詞是否出現在字串中的概念。 我們瞭解了 find() 方法如何幫助搜尋給定字串的單詞,另一方面,當此方法等於 string::pos 時,它返回出現在字串中的單詞,否則單詞不存在。

更新於: 2023年5月10日

785 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告