Count Occurrences of a Given Character in a String
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
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.
#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;
}
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));
}
}
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))
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));
}
}
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.
#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;
}
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)));
}
}
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.
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));
}
}
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.
#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));
}
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));
}
}
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))
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));
}
}
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.