Skip to content
Related Articles

Related Articles

Improve Article

Count of words ending at the given suffix in Java

  • Last Updated : 07 Dec, 2020

Given a string str consisting of a sentence, the task is to find the count of words in the given sentence that end with the given suffix suff.

Examples:  

Input: str = “GeeksForGeeks is a computer science portal for geeks”, suff = “ks” 
Output:
“GeeksForGeeks” and “geeks” are the only words ending with “ks”.

Input: str = “This is a sample string”, suff = “is” 
Output:

Approach:  



  • Extract all the words from the given sentence using the split() method.
  • Now for every word check whether the current words ends with the given suffix using endsWith() method.

Below is the implementation of the above approach:  

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
template <size_t N>
void splitString(string (&arr)[N], string str)
{
    int n = 0;
    istringstream iss(str);
     
    for(auto it = istream_iterator<string>(iss);
             it != istream_iterator<string>() && n < N;
           ++it, ++n)
        arr[n] = *it;
}
 
inline bool ends_with(std::string const& value,
                      std::string const& ending)
{
    if (ending.size() > value.size())
        return false;
         
    return std::equal(ending.rbegin(),
                      ending.rend(),
                      value.rbegin());
}
 
// Function to return the count of words
// in the given sentence that
// end with the given suffix
int endingWith(string str, string suff)
{
     
    // To store the count
    int cnt = 0;
    const int size = 50;
    string words[size];
     
    // Extract words from the sentence
    splitString(words, str);
     
    // For every word
    for(int i = 0; i < size; i++)
    {
         
        // If it ends with the given suffix
        if (ends_with(words[i], suff))
            cnt++;
    }
    return cnt;
}
 
// Driver code
int main()
{
    string str = "GeeksForGeeks is a computer "
                 "science portal for geeks";
    string suff = "ks";
 
    cout << endingWith(str, suff);
}
 
// This code is contributed by pratham76

Java




// Java implementation of the approach
class GFG {
 
    // Function to return the count of words
    // in the given sentence that
    // end with the given suffix
    static int endingWith(String str, String suff)
    {
 
        // To store the count
        int cnt = 0;
 
        // Extract words from the sentence
        String words[] = str.split(" ");
 
        // For every word
        for (int i = 0; i < words.length; i++) {
 
            // If it ends with the given suffix
            if (words[i].endsWith(suff))
                cnt++;
        }
 
        return cnt;
    }
 
    // Driver code
    public static void main(String args[])
    {
        String str = "GeeksForGeeks is a computer"
                     + " science portal for geeks";
        String suff = "ks";
 
        System.out.print(endingWith(str, suff));
    }
}

Python3




# Function declared to
# return the count of words
# in the given sentence that
# end with the given suffix
def endingWith( str , suff ):
     
    # Variable to store count
    c = 0
     
    # split function used to extract words
    # from sentence in form of list
    wrd = str.split(" ")
     
    # using for loop with 'in' to extract
    # elements of list
    for l in wrd:
        if l.endswith(suff):
            c += 1
             
    # returning the count
    return c
 
# Driver Code   
str = "GeeksForGeeks is a computer science portal for geeks"
suff = "ks"
 
# printing the final cde
print(endingWith(str, suff ))
 
# This code is contributed by Animesh_Gupta

C#




// C# implementation of the approach
using System;
class GFG{
  
  // Function to return the count of words
  // in the given sentence that
  // end with the given suffix
  static int endingWith(string str, string suff)
  {
 
    // To store the count
    int cnt = 0;
 
    string []sep = {" "};
 
    // Extract words from the sentence
    string []words = str.Split(sep,
                         StringSplitOptions.RemoveEmptyEntries);
 
    // For every word
    for (int i = 0; i < words.Length; i++)
    {
 
      // If it ends with the given suffix
      if (words[i].EndsWith(suff))
        cnt++;
    }
    return cnt;
  }
 
  // Driver code
  public static void Main(string []args)
  {
    string str = "GeeksForGeeks is a computer" +
                   " science portal for geeks";
    string suff = "ks";
 
    Console.Write(endingWith(str, suff));
  }
}
 
// This code is contributed by rutvik
Output: 
2

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :