使用 C++ 查詢一個字串的子字串在另一個字串中出現的次數
在本文中,我們給定兩個字串,我們需要找出第一個字串有多少個子字串可以在第二個字串中找到(相同的子字串可以出現多次)。例如
Input : string1 = “fogl” string2 = “google” Output : 6 Explanation : substrings of string1 present in string2 are [ “o”, “g”, “l”, “og”, “gl”, “ogl” ]. Input : string1 = “ajva” string2 = “java” Output : 5 Explanation : substrings of string1 present in string2 are [ “a”, “j”, “v”, “a”, “va” ].
尋找解決方案的方法
讓我們討論一下如何解決這個問題,即在一個字串中找到多個子字串;透過檢視示例,我們瞭解到首先,我們必須檢視字串 1 的所有子字串,然後檢查每個子字串是否出現在另一個字串中,如果存在,則遞增計數器,並在操作整個字串後檢查計數器中儲存的結果。
上述方法的 C++ 程式碼
這是我們可以用作輸入來解決給定問題的 C++ 語法 -
示例
#include<iostream> #include<string> using namespace std; int main() { string str1 = "ajva"; string str2 = "java"; int count = 0;// counter to store result int n = str1.length(); for (int i = 0; i < n; i++) { string str3; // string3 is initialised to store all substrings of string1 for (int j = i; j < n; j++) { str3 += str1[j]; // checking whether substring present in another string or not if (str2.find(str3) != string::npos) count++; } } cout << "Number of substrings of one string present in other : "<< count; return 0; }
輸出
Number of substrings of one string present in other : 5
理解程式碼
首先,在此程式碼中,我們為兩個字串賦予值並將計數器初始化為 0。我們遍歷整個字串並找到 str1 所有可能的子字串並將它們儲存在 str3 中。然後我們檢查 str1 的每個子字串是否出現在 str2 中;如果是,則將計數器加 1,最後我們列印儲存在計數器變數中的輸出。
結論
本文找到了查詢一個字串在另一個字串中出現的子字串數量的簡單解決方案。我們可以在其他語言(如 C、Java、Python 和其他語言)中編寫相同的程式。我們希望您覺得本文有所幫助。
廣告