Write a program to count the number of occurrences of a character in String is one of the common programming interview questions not just in Java but also in other programming languages like C or C++. As String in a very popular topic on programming interviews and there are a lot of good programming exercise on String like "count number of vowels or consonants in String", "count number of characters in String", How to reverse String in Java using recursion or without using StringBuffer, etc, it becomes extremely important to have a solid knowledge of String in Java or any other programming language. Though, this question is mostly used to test the candidate's coding ability i.e. whether he can convert logic to code or not.
In Interview, most of the time Interviewer will ask you to write a program without using any API method, as Java is very rich and it always some kind of nice method to do the job, But it also important to know rich Java and open source libraries for writing production-quality code.
Anyway, in this question, we will see both API based and non-API based(except few) ways to count a number of occurrences of a character in String on Java.
Also, basic knowledge of essential data structure and algorithms is also very important and that's why I suggest all Java programmers join a comprehensive Data Structure and Algorithms course like Data Structures and Algorithms: Deep Dive Using Java on Udemy to improve your knowledge and algorithms skills.
In Interview, most of the time Interviewer will ask you to write a program without using any API method, as Java is very rich and it always some kind of nice method to do the job, But it also important to know rich Java and open source libraries for writing production-quality code.
Anyway, in this question, we will see both API based and non-API based(except few) ways to count a number of occurrences of a character in String on Java.
Also, basic knowledge of essential data structure and algorithms is also very important and that's why I suggest all Java programmers join a comprehensive Data Structure and Algorithms course like Data Structures and Algorithms: Deep Dive Using Java on Udemy to improve your knowledge and algorithms skills.
Java program to count occurrences of a character in String

After that, we will see Apache commons StringUtils class for counting occurrence of a character in String. Apache commons StringUtils provide countMatches() method which can be used to count the occurrence of one character or substring.
Finally, we will see the most simple way of counting character using standard for loop and Java 5 enhanced for loop. This solution can be extended not just to finding the occurrence of character but also finding occurrences of a substring.
Btw, if you are solving this question as part of your Java interview preparation, you can also check Cracking the Coding Interview, a collection of 189 programming questions and solutions from various programming job interviews. Your perfect companion for developing coding sense required solving these kinds of problems on interviews.
import org.springframework.util.StringUtils;
/**
* Java program to count the number of occurrence of any character on String.
* @author Javin Paul
*/
public class CountCharacters {
public static void main(String args[]) {
String input = "Today is Monday"; //count number of "a" on this String.
//Using Spring framework StringUtils class for finding occurrence of another String
int count = StringUtils.countOccurrencesOf(input, "a");
System.out.println("count of occurrence of character 'a' on String: " +
* Java program to count the number of occurrence of any character on String.
* @author Javin Paul
*/
public class CountCharacters {
public static void main(String args[]) {
String input = "Today is Monday"; //count number of "a" on this String.
//Using Spring framework StringUtils class for finding occurrence of another String
int count = StringUtils.countOccurrencesOf(input, "a");
System.out.println("count of occurrence of character 'a' on String: " +
" Today is Monday' using Spring StringUtils " + count);
//Using Apache commons lang StringUtils class
int number = org.apache.commons.lang.StringUtils.countMatches(input, "a");
System.out.println("count of character 'a' on String: 'Today is Monday' using commons StringUtils " + number);
//counting occurrence of character with loop
int charCount = 0;
for(int i =0 ; i<input.length(); i++){
if(input.charAt(i) == 'a'){
charCount++;
}
}
System.out.println("count of character 'a' on String: 'Today is Monday' using for loop " + charCount);
//a more elegant way of counting occurrence of character in String using foreach loop
charCount = 0; //resetting character count
for(char ch: input.toCharArray()){
if(ch == 'a'){
charCount++;
}
}
System.out.println("count of character 'a' on String: 'Today is Monday' using for each loop " + charCount);
}
}
Output
count of occurrence of character 'a' on String: 'Today is Monday' using Spring StringUtils 2
count of character 'a' on String: 'Today is Monday' using commons StringUtils 2
count of character 'a' on String: 'Today is Monday' using for loop 2
count of character 'a' on String: 'Today is Monday' using for each loop 2
//Using Apache commons lang StringUtils class
int number = org.apache.commons.lang.StringUtils.countMatches(input, "a");
System.out.println("count of character 'a' on String: 'Today is Monday' using commons StringUtils " + number);
//counting occurrence of character with loop
int charCount = 0;
for(int i =0 ; i<input.length(); i++){
if(input.charAt(i) == 'a'){
charCount++;
}
}
System.out.println("count of character 'a' on String: 'Today is Monday' using for loop " + charCount);
//a more elegant way of counting occurrence of character in String using foreach loop
charCount = 0; //resetting character count
for(char ch: input.toCharArray()){
if(ch == 'a'){
charCount++;
}
}
System.out.println("count of character 'a' on String: 'Today is Monday' using for each loop " + charCount);
}
}
Output
count of occurrence of character 'a' on String: 'Today is Monday' using Spring StringUtils 2
count of character 'a' on String: 'Today is Monday' using commons StringUtils 2
count of character 'a' on String: 'Today is Monday' using for loop 2
count of character 'a' on String: 'Today is Monday' using for each loop 2
Well, the beauty of this questions is that Interviewer can twist it on many ways, they can ask you to write a recursive function to count occurrences of a particular character or they can even ask to count how many times each character has appeared.
So if a String contains multiple characters and you need to store count of each character, consider using HashMap for storing character as key and number of occurrence as value. Though there are other ways of doing it as well but I like the HashMap way of counting character for simplicity.
So if a String contains multiple characters and you need to store count of each character, consider using HashMap for storing character as key and number of occurrence as value. Though there are other ways of doing it as well but I like the HashMap way of counting character for simplicity.
Further Learning
The Coding Interview Bootcamp: Algorithms + Data Structures
Data Structures and Algorithms: Deep Dive Using Java
Algorithms and Data Structures - Part 1 and 2
Other programming exercises for Java programmer
32 comments :
Collections.frequency() method might be useful in this case.
public class test
{
public static void main(String[] args)
{
String str = "ababccbdde";
int i,j,k;
char[] ch = str.toCharArray();
int len=ch.length;
for ( i = 0; i < len; i++) {
int counter = 0;
char c=str.charAt(i);
for ( j = 0; j < len; j++) {
if (c==ch[j]){
counter++;
ch[j]='\u0000';
}
}
if(counter>0)System.out.println(c+"="+counter);
}
}
}
package selfpractice.array;
public class DistinctArray2 {
static String str = "sgsgsgsgs";
static String distinct = "";
static char[] charary = str.toCharArray();
static StringBuilder hello = new StringBuilder("");
static char[] tempcharary = new char[charary.length];
static int i;
static int count;
public static char[] getDistinctLetter()
{
int incr = 0;
for ( i = 0; i < charary.length; i++)
{
if (!(DistinctArray2.isletteroccure(charary[i])))
{
tempcharary[incr] = charary[i];
hello.append( tempcharary[incr]);
++incr;
}
}
char[] distinctresult = hello.toString().toCharArray();
for (int j = 0; j < distinctresult.length; j++)
{
for (int k = 0; k < charary.length; k++)
{
if (distinctresult[j] == charary[k])
{
++count;
}
}
System.out.println("LETTER " + tempcharary[j] + " OCCURE " + count + " TIMES ");
count = 0;
}
return tempcharary;
}
public static Boolean isletteroccure(char ch)
{
for (int j = 0; j < charary.length; j++)
{
if (ch == tempcharary[j])
{
return true;
}
}
return false;
}
public static void main(String[] args) {
DistinctArray2.getDistinctLetter();
}
}
Program to accept the string from command line and display
1. No. of words in string
2. No. of characters in each word
3. No. of characters in string
public class Str
{
public static void main(String args[])
{
int ch=0;
System.out.println("String is = ");
for(int i=0;i<args.length;i++)
{
System.out.println(args[i]);
}
System.out.println("Number of words in the string = "+args.length);
for(int i=0;i<args.length;i++)
{
String s=args[i];
ch=s.length()+ch;
System.out.println("Number of characters in -"+args[i]+"- = "+s.length());
}
System.out.println("No. of characters in string = "+ch);
System.out.println("No. of characters in string with white spaces ="+(ch+(args.length-1)));
}
}
package String;
import java.util.Scanner;
public class Reverse {
@SuppressWarnings("resource")
public static void main(String[] args) {
int charCount = 0;
System.out.println("Enter the string:");
Scanner in = new Scanner(System.in);
String str = in.nextLine();
for(char ch = 'a' ; ch <= 'z' ; ch++ )
{
for(int i =0 ; i<str.length()-1; i++)
{
if(str.charAt(i) == ch)
{
charCount++;
}
}
if(charCount!=0){
System.out.println(ch+"="+charCount);
charCount=0;
}
}
}
}
public class Binary_Octal {
Scanner scan;
int num;
void getVal() {
System.out.println("Binary to Octal");
scan = new Scanner(System.in);
System.out.println("\nEnter the number :");
num = Integer.parseInt(scan.nextLine(), 2);
}
void convert() {
String octal = Integer.toOctalString(num);
System.out.println("Octal Value is : " + octal);
}
}
class MainClass {
public static void main(String args[]) {
Binary_Octal obj = new Binary_Octal();
obj.getVal();
obj.convert();
}
}
Sample Output
Binary to Octal
Enter the number :
1010
Octal Value is : 12
import java.util.Scanner;
public class count {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
System.out.println("Enter String");
String str = scn.nextLine();
System.out.println("Enter charcter to know its occurrence");
char c = scn.next().charAt(0);
int count =0;
for(int i=0;i<str.length();i++){
char ch = str.charAt(i);
if(ch==c){
count++;
}
}
System.out.println("count is:"+count);
}
}
Hello Vandana, time complexity of your solution is O(n) as it need to iterate through array, can you better it?
Scanner s = new Scanner(System.in);
System.out.println("Enter some sentence");
String sentence = s.nextLine();
System.out.println("Enter word to to follow ");
char word = s.next().charAt(0);
int counter =0;
char[] chars = sentence.toCharArray();
for (int i = 0; i < chars.length; i++) {
System.out.print("| " + i + " |");
System.out.println(" " + chars[i] + " |");
System.out.println("-------------");
}
for (int i = 0; i < chars.length; i++) {
if(sentence.charAt(i) == word){
counter++;
}
}
System.out.println("Word " + word + " appears in sentence " + counter + " times");
s.close();
count the no of characters in a string
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
String s= " hello srikanth";
int count=0;;
for(int i=0;i<s.length();i++)
{boolean b=Character.isWhitespace(s.charAt(i));
if(b==false)
{
count++;
}
}
System.out.println(count);
}
}
id this fine or not
static int c = 0;
public static void main(String[] args) {
String s = "aabbcfasdgalsgmvxnxbcsasfweasdgkandjkakjgaasdg";
char[] chars = s.toCharArray();
Arrays.sort(chars);
String sortedString = new String(chars);
count(sortedString);
}
public static void count(String str) {
char[] chars = str.toCharArray();
Set set = new HashSet();
for(int i = 0; i < chars.length; i ++) {
set.add(chars[i]);
}
List list = new ArrayList();
for (Character string : set) {
list.add(string);
int occ = StringUtils.countOccurrencesOf(str, string.toString());
System.out.print(string.toString() + occ);
}
}
Use regular expressions
Hello @Matt, can you please share the regular expression to count occurrence of any character in string, that will help better ..
Hello All, I m a beginner in java . I need to write a program for below:
Given a Sentence , i need to color a sentence using minimum no. of Consonants. Each word in sentence can be colored by a single consonant
ex: Hello How are you?
Minimum no. of consonant to color sentence : 2
i.e using o,e ( o occurs in 3 words: Hello,How ,you & e in are )
therefore answer is 2
Please help
str.split(c).length() - 1
String s="helppp";
int c=0;
char o=0;
for (int i = 0; i 0)
{
System.out.println("char is repeated "+o+" at "+c+" times");
}
else
{
System.out.println("no char is repeated");
}
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class OccurenceofChar {
public static void main(String[] args) {
// TODO Auto-generated method stub
Occurence occur=new Occurence();
occur.Occurence("Today is Monday", 'o');
}
}
class Occurence{
public static int Occurence(String word, char letter) {
Map map=new HashMap<>();
char c[]=word.toCharArray();
for(Character ch:c) {
if(map.containsKey(ch)) {
map.put(ch,map.get(ch)+1);
}
else {
map.put(ch, 1);
}
}
Set> entryset=map.entrySet();
int occurence=0;
for(Map.Entry entry: entryset) {
if(entry.getKey()==letter) {
occurence=entry.getValue();
}
}
System.out.println(occurence);
return occurence;
}
}
Nice solution, what are the test cases you have thought? Can you explain the Big(O) for space and time?
Wow surprised no one solved this recursively. Here you go with binary search:
public static void main(String[] args) {
int x = stringCounter("abacaaadeaac");
System.out.println(x);
}
public static int stringCounter(String string){
if(string.length() < 2){
if(string.contains("a")){
return 1;
}
return 0;
}
return stringCounter(string.substring(0,string.length()/2)) + stringCounter(string.substring(string.length()/2));
}
}
Recursive solution is good idea but I guess you need one more parameter to count occurence of a given character, right now you are just counting "a"
import java.util.*;
public class solution {
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
String in=s.nextLine();
char c[]=in.toCharArray();
List b=new ArrayList();
for(char addchar:c)
{
b.add(addchar);
}
int g=0;
int j=0;
for(int i=0;ig)
{
j=i;
g=n;
}
}
System.out.println(c[j]);
}
}
function run() {
var value = "add something here with many characters";
var array = value.split("");
var occurrences = {};
array.forEach(function(val) {
if(occurrences[val] == null || occurrences[val] == undefined){
occurrences[val] = 1;
} else {
occurrences[val] += 1;
}
});
console.log(occurrences);
}
public static void main(String[]args){
String s="laxmikanta";
int count=s.length()-s.replace("a","").length();
System.out.println("No of occurrence of a is:"+count);
Good way to solve this problem for all characters.
import java.util.Scanner;
public class HelloWorld{
public static void main(String []args){
// System.out.println("Hello World");
Scanner sc=new Scanner(System.in);
String str=sc.nextLine();
int l=str.length();
int max=0,temp=0,k=0;
for(int i=0;imax)
{
max=temp;
k=i;
}
}
System.out.println("Character "+str.charAt(k)+" with max count "+max);
}
}
Hello @Unknown, blogger at the < sign, I assume its i < max right?
import java.util.*;
class MaximumOccurring{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
String str=sc.nextLine();
char ch[]=str.toCharArray();
char temp;
for(int i=0;ich[j]){
temp=ch[i];
ch[i]=ch[j];
ch[j]=temp;
}
}
}
int count=1;
int arr[]=new int[str.length()];
int k=0;
char result[]=new char[str.length()];
for(int i=0;imax){
max=arr[i];
index=i;
}
}
System.out.println(ch[index]);
}
}
Hello all, String val=banana , a has been occurred 3 times, can any one help an code , i am new to coding.
did you try this code?
using Java 8
Stream charStream = word.chars().mapToObj(obj -> (char) obj);
System.out.println(charStream.filter(c -> c == character).count());
neat example Anshul, thx for sharing with us.
Post a Comment