使用 C++ 列印給定陣列中所有作為給定字串子字串出現的字串


在程式設計世界中,有很多場景需要我們在更大的文字中查詢特定模式。一個常見的任務是從給定陣列中查詢並列印所有作為給定字串子字串出現的字串。這個看似基本的問題可以使用各種方法解決,在這篇文章中,我們將探討其中兩種方法。我們將對每種方法使用的語法和演算法進行明確的解釋,並附帶兩個完整的可執行程式碼示例。

語法

在我們深入探討方法之前,讓我們首先了解我們將用來解決這個問題的語法。

void printMatchingStrings(string array[], string text);

演算法

為了解決查詢並列印陣列中所有作為給定字串子字串出現的字串的問題,我們可以遵循以下分步演算法:

  • 初始化一個空向量來儲存匹配的字串。

  • 重複遍歷陣列中的每個字串。

  • 檢查當前字串是否是給定文字的子字串。

  • 如果是,則將字串新增到匹配字串的向量中。

  • 遍歷所有字串後,列印匹配字串的向量。

方法 1:使用 string.find() 函式

在此方法中,我們將使用 string.find() 函式,該函式返回子字串在字串中的位置。如果找不到子字串,則返回一個特殊值,稱為 string::npos。

示例

#include <iostream>
#include <vector>
#include <string>

void printMatchingStrings(const std::string array[], const std::string& text, int arraySize) {
   std::vector<std::string> matchingStrings;

   for (int i = 0; i < arraySize; i++) {
      if (text.find(array[i]) != std::string::npos) {
         matchingStrings.push_back(array[i]);
      }
   }

   for (const std::string& match : matchingStrings) {
      std::cout << match << std::endl;
   }
}

int main() {
   const std::string array[] = { "apple", "banana", "orange", "pear" };
   const std::string text = "I like to eat bananas and oranges.";

   int arraySize = sizeof(array) / sizeof(array[0]);

   printMatchingStrings(array, text, arraySize);

   return 0;
}

輸出

banana
orange

方法 2:使用正則表示式

正則表示式提供了一個強大的工具來進行字串模式匹配。我們也可以利用它們來解決我們的問題。

示例

#include <iostream>
#include <vector>
#include <string>
#include <regex>

void printMatchingStrings(const std::string array[], const std::string& text, int arraySize) {
   std::vector<std::string> matchingStrings;

   for (int i = 0; i < arraySize; i++) {
      std::regex pattern(array[i]);

      if (std::regex_search(text, pattern)) {
         matchingStrings.push_back(array[i]);
      }
   }

   for (const std::string& match : matchingStrings) {
      std::cout << match << std::endl;
   }
}

int main() {
   const std::string array[] = { "apple", "banana", "orange", "pear" };
   const std::string text = "I like to eat bananas and pear.";

   int arraySize = sizeof(array) / sizeof(array[0]);

   printMatchingStrings(array, text, arraySize);

   return 0;
}

輸出

banana
pear

選擇正確的方法

兩種方法的選擇取決於特定問題的需求:

如果使用 string.find() 方法:

要匹配的模式相對簡單。

效能是一個問題,因為對於簡單的模式,string.find() 方法可能比正則表示式更快。

您更喜歡更簡單的實現,無需正則表示式語法。

如果使用正則表示式方法:

要匹配的模式很複雜,需要高階模式匹配功能。

模式匹配的靈活性和強大功能非常重要。

效能不是關鍵因素,或者模式的複雜性證明了使用正則表示式的合理性。

結論

在本文中,我們探討了兩種獨特的方法來解決查詢並列印陣列中所有作為給定字串子字串出現的字串的問題。主要方法使用了 string.find() 函式,這是一個簡單直接的解決方案。後續方法利用正則表示式的強大功能來處理更復雜的模式匹配情況。根據特定問題的需求,您可以選擇最合適的方法。請記住,模式匹配是程式設計中的一項基本任務,對各種方法和策略有紮實的理解可以顯著提高您的問題解決能力。因此,下次遇到類似問題時,您將掌握有效處理它的知識。

更新於:2023年7月25日

瀏覽量:126

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.