Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Count occurrences of a character in a repeated string
Next article icon

Count Occurrences of a Given Character in a String

Last Updated : 10 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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.

Table of Content

  • Linear Search
  • Using Inbuilt Functions
  • Using Recursion – Not Efficient (Only for Learning Purpose)

Linear Search

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

C++
#include <bits/stdc++.h> using namespace std;   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
class GfG {      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;     }           public static void main(String args[])     {         String str= "geeksforgeeks";         char c = 'e';         System.out.println(count(str, c));     } } 
Python
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           str= "geeksforgeeks" c = 'e' print(count(str, c))      
C#
using System;          public class GfG {     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;     }          public static void Main()     {         string str = "geeksforgeeks";         char c = 'e';                  Console.WriteLine(count(str, c));     } } 
JavaScript
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; }         let str= "geeksforgeeks";     let c = 'e';     console.log(count(str, c)); 

Output
4 

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

Using Inbuilt Functions

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

C++
#include<bits/stdc++.h> using namespace std;  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)));     } } 
Python
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';          Console.WriteLine(str.Count(x => x == c));     } } 
JavaScript
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(n), where n is the size of the string given.
Auxiliary Space: O(1) 

Using Recursion – Not Efficient (Only for Learning Purpose)

This approach uses recursion 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.

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 GfG {     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));     } } 
Python
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 GfG {      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(n), where n is the size of string given.
Auxiliary Space: O(n), due to the recursion stack, where n is the size of string.



Next Article
Count occurrences of a character in a repeated string

S

Sahil Rajput
Improve
Article Tags :
  • C++
  • Competitive Programming
  • DSA
  • Strings
Practice Tags :
  • CPP
  • Strings

Similar Reads

  • Count occurrences of a character in a repeated string
    Given an integer N and a lowercase string. The string is repeated infinitely. The task is to find the No. of occurrences of a given character x in first N letters.Examples: Input : N = 10 str = "abcac"Output : 4Explanation: "abcacabcac" is the substring from the infinitely repeated string. In first
    8 min read
  • Find the Nth occurrence of a character in the given String
    Given string str, a character ch, and a value N, the task is to find the index of the Nth occurrence of the given character in the given string. Print -1 if no such occurrence exists. Examples: Input: str = "Geeks", ch = 'e', N = 2 Output: 2 Input: str = "GFG", ch = 'e', N = 2 Output: -1 Recommended
    7 min read
  • Count occurrence of a given character in a string using Stream API in Java
    Given a string and a character, the task is to make a function which counts the occurrence of the given character in the string using Stream API. Examples: Input: str = "geeksforgeeks", c = 'e' Output: 4 'e' appears four times in str. Input: str = "abccdefgaa", c = 'a' Output: 3 'a' appears three ti
    1 min read
  • Count of camel case characters present in a given string
    Given a string S, the task is to count the number of camel case characters present in the given string. The camel case character is defined as the number of uppercase characters in the given string. Examples: Input: S = "ckjkUUYII"Output: 5Explanation: Camel case characters present are U, U, Y, I an
    7 min read
  • Count the number of unique characters in a given String
    Given a string, str consisting of lowercase English alphabets, the task is to find the number of unique characters present in the string. Examples: Input: str = “geeksforgeeks”Output: 7Explanation: The given string “geeksforgeeks” contains 7 unique characters {‘g’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’}. Inp
    14 min read
  • Count occurrences of a word in string
    Given a two strings s and word. The task is to count the number of occurrences of the string word in the string s.Note: The string word should appear in s as a separate word, not as a substring within other words. Examples: Input: s = "GeeksforGeeks A computer science portal for geeks", word = "port
    11 min read
  • Count occurrences of a sub-string with one variable character
    Given two strings a and b, and an integer k which is the index in b at which the character can be changed to any other character, the task is to check if b is a sub-string in a and print out how many times b occurs in a in total after replacing the b[k] with every possible lowercase character of Eng
    5 min read
  • Find maximum occurring character in a string
    Given string str. The task is to find the maximum occurring character in the string str. Examples: Input: geeksforgeeksOutput: eExplanation: 'e' occurs 4 times in the string Input: testOutput: tExplanation: 't' occurs 2 times in the string Return the maximum occurring character in an input string us
    9 min read
  • Count of occurrences of a "1(0+)1" pattern in a string
    Given an alphanumeric string, find the number of times a pattern 1(0+)1 occurs in the given string. Here, (0+) signifies the presence of non empty sequence of consecutive 0's. Examples: Input : 1001010001 Output : 3 First sequence is in between 0th and 3rd index. Second sequence is in between 3rd an
    7 min read
  • Count of 1-bit and 2-bit characters in the given binary string
    Given two special characters, the first character can be represented by one bit which is 0 and the second character can be represented by two bits either 10 or 11. Now given a string represented by several bits. The task is to return the number of characters it represents. Note that the given string
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences