C++中給定字串長度為n的子字串計數


給定一個字串str[]和一個數字n。目標是找到str[]中所有長度為n的子字串。如果字串是“abcde”並且n=3,則長度為3的子字串是“abc”、“bcd”、“cde”,計數為3。

讓我們透過例子來理解。

輸入 − str[] = “computer” n=4

輸出 − 給定字串中長度為n的子字串個數為:5

說明 − 長度為4的子字串為:“comp”,“ompu”,“mput”,“pute”,“uter”

輸入 − str[] = “development” n=5

輸出 − 給定字串中長度為n的子字串個數為:7

說明 − 長度為5的子字串為:“devel”,“evelo”,“velop”,“elopm”,“lopme”,“opmen”,“pment”。

下面程式中使用的方法如下

如果我們將字串str[]的長度作為L,則str[]內長度為n的子字串的個數為L-n+1。如果字串是“abcdefghi”並且n是4,則子字串將是“abcd”,“bcde”,“cdef”,“defg”,“efgh”,“fghi”。個數是6。同時9-4+1=6。

  • 取一個字串str。

  • 取n為整數。

  • 函式possible_substring(string str, int length, int n)接受一個字串、它的長度n並返回str中長度為n的子字串的個數。

  • 取一個變數count。

  • 設定count = length-n+1。

  • 最後返回count作為結果。

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
int possible_substring(string str, int length, int n){
   int count = length - n + 1;
   return count;
}
int main(){
   string str = "learning";
   int length = str.length();
   int n = 2;
   cout<<"Count of substrings of length n possible from the given string are: "<<possible_substring(str, length, n);
   return 0;
}

輸出

如果我們執行上面的程式碼,它將生成以下輸出:

Count of substrings of length n possible from the given string are: 7

更新於:2020年12月2日

585 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告