Count Occurrences of a Given Character in a String
Last Updated :
10 Apr, 2025
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.
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));
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);
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));
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.
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
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 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
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
Count of substrings having all distinct characters Given a string str consisting of lowercase alphabets, the task is to find the number of possible substrings (not necessarily distinct) that consists of distinct characters only.Examples: Input: Str = "gffg" Output: 6 Explanation: All possible substrings from the given string are, ( "g", "gf", "gff",
7 min read
Count the number of Unique Characters in a String in Python We are given a string, and our task is to find the number of unique characters in it. For example, if the string is "hello world", the unique characters are {h, e, l, o, w, r, d}, so the output should be 8.Using setSet in Python is an unordered collection of unique elements automatically removing du
2 min read
Count the Number of matching characters in a pair of strings Given a pair of non-empty strings str1 and str2, the task is to count the number of matching characters in these strings. Consider the single count for the character which have duplicates in the strings.Examples: Input: str1 = "abcdef", str2 = "defghia" Output: 4 Matching characters are: a, d, e, fI
7 min read
Count of strings that does not contain any character of a given string Given an array arr containing N strings and a string str, the task is to find the number of strings that do not contain any character of string str. Examples: Input: arr[] = {"abcd", "hijk", "xyz", "ayt"}, str="apple"Output: 2Explanation: "hijk" and "xyz" are the strings that do not contain any char
8 min read