Count strings that end with the given pattern in C++

C++Server Side ProgrammingProgramming

We are given an array of strings str[] and a pattern string pat. The goal is to find the string elements of str[] that have pattern pat at the end.

We will traverse each string of str and compare last characters with pat. If they match increment

Let’s understand with examples.

Input 

str[]={ “kittens”, “hens”, “deers”, “dogs” } pat=”ens”

Output 

Strings that end with given pattern: 2

Explanation 

Strings “kitt-ens” and “h-ens” end with “ens”.

Input 

str[]={ “tickets”, “wickets”, “bats”, “cricket” } pat=”et”

Output 

Strings that end with given pattern: 1

Explanation 

Strings “wick-et” ends with “et”.

Approach used in the below program is as follows

  • We string array str[] and a pattern string pat.

  • N is no of strings in str[].

  • Function endPattern(string str[], int n, string ptr) returns the count of strings in str that end with given pattern

  • Take the initial variable count as 0.

  • Traverse using for loop from i=1 to i<n

  • Take each string str[i] as s. Let slen be s.length().

  • Take plen=ptr.lenght(). Take flag=1.

  • Now decreent plen and slen by 1 to get the last indexes of string s and pattern ptr.

  • Using while loop check until plen>=0.

  • If any s[slen]!=ptr[plen]. Set flag=0 and break the loop. Otherwise decrement plen and slen to check the next character from end.

  • After the while ends, if flag is still 1 then increment count as ptr occurs in s.

  • Return count after end of all loops which is count of strings ending with given pattern.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int endPattern(string str[], int n, string ptr){
   int count=0;
   for(int i=0;i<n;i++){
      string s=str[i];
      int slen=s.length();
      int plen=ptr.length();
      int flag=1;
      slen--; //last index
      plen--;
      while(plen>=0){
         if(ptr[plen]!=s[slen]){
            flag=0;
            break;
         }
         plen--;
         slen--;
      }
      if(flag==1)
         { count++; }
   }
   return count;
}
int main(){
   string patrn = "pes";
   int N = 4;
   string str[] = { "stripes", "cars", "ripes", "pipes" };
   cout <<"Strings that end with given pattern: "<<endPattern(str,N,patrn);
   return 0;
}

Output

If we run the above code it will generate the following output −

Strings that end with given pattern: 3
raja
Published on 31-Oct-2020 09:48:18
Advertisements