Open In App

Program to count occurrence of a given character in a string

Improve
Improve
Like Article
Like
Save
Share
Report

Given a string S and a character ‘c’, the task is to count the occurrence of the given character in the string.

Examples:  

Input : S = “geeksforgeeks” and c = ‘e’
Output : 4
Explanation: ‘e’ appears four times in str.

Input : S = “abccdefgaa” and c = ‘a’
Output : 3
Explanation: ‘a’ appears three times in str.

Count occurrence of a given character in a string using simple Iteration:

Iterate through the string and during each iteration, check if the current character is equal to the given character c then increments the count variable which stores count of the occurrences of the given character c in the string.

Below is the implementation of above approach:

C++




// C++ program to count occurrences of a given
// character
#include <iostream>
#include <string>
using namespace std;
 
// Function that return count of the given
// character in the string
int count(string s, char c)
{
    // Count variable
    int res = 0;
 
    for (int i=0;i<s.length();i++)
 
        // checking character in string
        if (s[i] == c)
            res++;
 
    return res;
}
 
// Driver code
int main()
{
    string str= "geeksforgeeks";
    char c = 'e';
    cout << count(str, c) << endl;
    return 0;
}


Java




// JAVA program to count occurrences
// of a character
 
class GFG
{
    // Method that return count of the given
    // character in the string
    public static int count(String s, char c)
    {
        int res = 0;
 
        for (int i=0; i<s.length(); i++)
        {
            // checking character in string
            if (s.charAt(i) == c)
            res++;
        }
        return res;
    }
     
    // Driver method
    public static void main(String args[])
    {
        String str= "geeksforgeeks";
        char c = 'e';
        System.out.println(count(str, c));
    }
}


Python3




# Python program to count occurrences
# of a given character
 
# Method that return count of the
# given character in the string
def count(s, c) :
     
    # Count variable
    res = 0
     
    for i in range(len(s)) :
         
        # Checking character in string
        if (s[i] == c):
            res = res + 1
    return res
     
     
# Driver code
str= "geeksforgeeks"
c = 'e'
print(count(str, c))
     
# This code is contributed by "rishabh_jain".


C#




// C# program to count occurrences
// of a character
using System;
         
public class GFG {
     
    // Method that return count of the given
    // character in the string
    public static int count(string s, char c)
    {
        int res = 0;
 
        for (int i = 0; i < s.Length; i++)
        {
             
            // checking character in string
            if (s[i] == c)
            res++;
        }
         
        return res;
    }
     
    // Driver method
    public static void Main()
    {
        string str = "geeksforgeeks";
        char c = 'e';
         
        Console.WriteLine(count(str, c));
    }
}
 
// This code is contributed by Sam007.


Javascript




<script>
// JAVASCRIPT program to count occurrences
// of a character
    // Method that return count of the given
    // character in the string
    function count(s, c)
    {
        let res = 0;
 
        for (let i = 0; i < s.length; i++)
        {
            // checking character in string
            if (s.charAt(i) == c)
            res++;
        }
        return res;
    }
     
    // Driver method  
        let str= "geeksforgeeks";
        let c = 'e';
        document.write(count(str, c));
         
 // This code is contributed by shivanisinghss2110      
 </script>


PHP




<?php
// PHP program to count
// occurrences of a given
// character
 
// Function that return count of
// the given character in the string
function count($s, $c)
{
     
    // Count variable
    $res = 0;
 
    for ($i = 0; $i < strlen($s); $i++)
 
        // checking character in string
        if ($s[$i] == $c)
            $res++;
 
    return $res;
}
 
    // Driver Code
    $str= "geeksforgeeks";
    $c = 'e';
    echo count($str, $c) ;
    return 0;
     
// This code is contributed by nitin mittal.
?>


Output

4

Time Complexity: O(len), where len is the size of the string given.
Auxiliary Space: O(1)

Count occurrence of a given character in a string using Inbuild Functions:

The idea is to use inbuild method in different programming languages which returns the count of occurences of a character in a string.

Below is the implementation of above approach:

C++




// CPP program to count occurrences of
// a character using library
#include<bits/stdc++.h>
using namespace std;
 
// Driver code
int main()
{
    string str = "geeksforgeeks";
    char c = 'e';
   
    // Count returns number of occurrences of
    // c between two given positions provided
    // as two iterators.
    cout << count(str.begin(), str.end(), c);
    return 0;
}


Java




import java.util.*;
 
public class Main {
    public static void main(String[] args)
    {
        String str = "geeksforgeeks";
        char c = 'e';
 
        // Count returns number of occurrences of
        // c between two given positions provided
        // as two iterators.
        System.out.println(Collections.frequency(
            Arrays.asList(str.split("")),
            String.valueOf(c)));
    }
}


Python3




# Python program to count occurrences of
# a character using library
 
# Driver code to test above function
str = "geeksforgeeks"
c = 'e'
 
# Count returns number of occurrences of
# c between two given positions provided
# as two iterators.
print(len(str.split(c)) - 1);
 
# The code is contributed by Arushi Goel.


C#




using System;
using System.Linq;
 
class Program {
    static void Main(string[] args) {
        string str = "geeksforgeeks";
        char c = 'e';
 
        // Count returns number of occurrences of
        // c between two given positions provided
        // as two iterators.
        Console.WriteLine(str.Count(x => x == c));
    }
}


Javascript




// JavaScript program to count occurrences of
// a character using library
 
// Driver code to test above function
let str = "geeksforgeeks";
let c = 'e';
 
// Count returns number of occurrences of
// c between two given positions provided
// as two iterators.
console.log(str.split(c).length - 1);


Output

4

Time Complexity: O(len), where len is the size of the string given.
Auxiliary Space: O(1) 

Count occurrence of a given character in a string using Recursion

Use a recursive approach to count the occurrences of a given character in a string. Checks if the character at the current index matches the target character, increments the count if it does, and then makes a recursive call to check the remaining part of the string. The process continues until the end of the string is reached, and the accumulated count would be the result.

Below is the implementation of above approach:

C++




#include<bits/stdc++.h>
using namespace std;
 
int countinString(char ch,int idx, string s)
{
    // base case;
    if (idx == s.size())
        return 0;
        int count = 0;
 
    // checking if the current character of
    // the given string is that character
    // or not
    if (s[idx] == ch)
        count++;
 
        // this will count the occurrence of
        // given character in the string
        // from the remaining part of the string.
    count += countinString(ch,idx+1,s);
 
    return count;
}
 
int main(){
    string str = "geeksforgeeks";
    char c = 'e';
    cout<<(countinString(c,0, str));
}


Java




public class Main {
    // Function to count occurrences of a character in a string
    public static int countInString(char ch, int idx, String s) {
        // Base case: if the index reaches the end of the string, return 0
        if (idx == s.length())
            return 0;
         
        int count = 0;
 
        // Check if the current character of the string matches the given character
        if (s.charAt(idx) == ch)
            count++;
 
        // Recursively count occurrences in the remaining part of the string
        count += countInString(ch, idx + 1, s);
 
        return count;
    }
 
    public static void main(String[] args) {
        String str = "geeksforgeeks";
        char c = 'e';
        System.out.println(countInString(c, 0, str));
    }
}


Python3




def count_in_string(ch, idx, s):
    # Base case: if the index reaches the end of the string, return 0
    if idx == len(s):
        return 0
 
    count = 0
 
    # Check if the current character of the string matches the given character
    if s[idx] == ch:
        count += 1
 
    # Recursively count occurrences in the remaining part of the string
    count += count_in_string(ch, idx + 1, s)
 
    return count
 
if __name__ == "__main__":
    str = "geeksforgeeks"
    c = 'e'
    print(count_in_string(c, 0, str))


C#




using System;
 
class Program {
    // Function to count occurrences of a character in a string
    static int CountInString(char ch, int idx, string s) {
        // Base case: if the index reaches the end of the string, return 0
        if (idx == s.Length)
            return 0;
         
        int count = 0;
 
        // Check if the current character of the string matches the given character
        if (s[idx] == ch)
            count++;
 
        // Recursively count occurrences in the remaining part of the string
        count += CountInString(ch, idx + 1, s);
 
        return count;
    }
 
    static void Main(string[] args) {
        string str = "geeksforgeeks";
        char c = 'e';
        Console.WriteLine(CountInString(c, 0, str));
    }
}


Javascript




function countInString(ch, idx, s) {
    // Base case: if the index reaches the end of the string, return 0
    if (idx === s.length)
        return 0;
 
    let count = 0;
 
    // Check if the current character of the string matches the given character
    if (s[idx] === ch)
        count++;
 
    // Recursively count occurrences in the remaining part of the string
    count += countInString(ch, idx + 1, s);
 
    return count;
}
 
const str = "geeksforgeeks";
const c = 'e';
console.log(countInString(c, 0, str));


Output

4

Time Complexity: O(len), where len is the size of the string given.
Auxiliary Space: O(len), where len is the size of the string given.



Last Updated : 20 Sep, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads