Read Also : Count number of words in the String with Example
So to be prepared for such types of questions I have shared the program code below.
Input string: "Alive is awesome"
Character to count: 'A'
Output : A=1
Note : The result is case sensitive, which means the uppercase and
lowercase alphabet are treated differently.
Read Also : Find first Non-Repeated Character in the String
Count Occurrences of Character in String in Java
1. Using Core Java Libraries
1.1 Using String class charAt() method
The simplest and easiest way to count occurrences of a character in a string is by using the charAt() method.Logic
a. Iterate through the entire length of the String
b. If the character to be searched matches with the character of the inputString then increase count by 1 else do nothing.
Let's find out the implementation:
public class CountOccurrencesOfCharacter { public static void main(String args[]) { // Given String String inputString = "LoveYourself"; // Character to be searched, here 'o' char searchChar = 'o'; int count = 0; for(int i=0; i < inputString.length(); i++) { if(inputString.charAt(i) == searchChar) { count++; } } System.out.println("Character "+searchChar+" appears in the inputString "+count+" times"); } }
Output:
Character o appears in the inputString 2 times
1.2 Using recursion
This is a bit tricky solution. We have invoked recursion by calling findOccurrence(inputString, searchChar, 0) i.e. findOccurrence("BeInPresent", 'e', 0). Adding 1 to the index every time we call findOccurrence until we traverse the length of the inputString.Let's find out the implementation:
public class CountOccurrencesOfCharacter2 { public static void main(String args[]) { // Given Input String String inputString = "BeInPresent"; // Character to be searched, here 'e' char searchChar = 'e'; // Using recursion, index 0 for start of string int result = findOccurrence(inputString, searchChar, 0); System.out.println("Character "+searchChar+" appears in the inputString "+result+" times"); } public static int findOccurrence(String str, char searchChar, int index) { int count = 0; // Base condition if(index >= str.length()) return 0; if(searchChar == str.charAt(index)) count++; return count + findOccurrence(str, searchChar, index+1); } }
Output:
Character e appears in the inputString 3 times
2. Using HashMap
We can also use HashMap to count occurrences of Character in String in java. It will have Character as key and its count occurrences as value. First, we will convert the given string into a char array. Then, we will traverse the char array and increment its value by 1 for each Character present in the input string.
import java.util.HashMap; public class CountOccurrencesOfCharacter3
{
public static void main(String[] args) { characterCount("Alive is Awesome"); characterCount("Java Hungry"); characterCount("USA has 50 states"); }
static void characterCount(String inputString) { //Creating a HashMap, key :Character value : occurrences as Integer HashMap<Character, Integer> eachCharCountMap = new HashMap<Character, Integer>(); //Converting inputString to char array char[] charArray = inputString.toCharArray(); //traversal of each Character of charArray for (char c : charArray) { if(eachCharCountMap.containsKey(c)) { //If char is present in eachCharCountMap, increment count by 1 eachCharCountMap.put(c, eachCharCountMap.get(c)+1); } else { //If char is not present in eachCharCountMap, //Putting this char to eachCharCountMap with 1 as it's initial value eachCharCountMap.put(c, 1); } } //Showing the eachCharCountMap System.out.println(eachCharCountMap); } }
Output:
{ =2, A=1, a=1, s=2, e=3, v=1, w=1, i=2, l=1, m=1, o=1} { =1, a=2, r=1, u=1, v=1, g=1, H=1, y=1, J=1, n=1} { =3, 0=1, A=1, a=2, S=1, s=3, t=2, U=1, 5=1, e=1, h=1}
3. Using Java 8 Features
Using Java 8 and above, we can use the streams and lambdas to count occurrences of character in String in Java.
import java.util.*; public class CountOccurencesOfCharacter4 { public static void main(String args[]) { // Given Input String String inputString = "DoNotProcastinate"; // Character to be searched, here 'a' char searchChar = 'a';
//3.1 Using chars() method /* chars() method returns a streams of ints(IntStream) that represent the character codes */ long count = inputString.chars().filter(ch -> ch == searchChar).count(); System.out.println("Character "+searchChar+" appears in the inputString "+count+" times");
//3.2 Using codePoints() method /* codePoints() method return the actual Unicode values of the stream */ char searchChar2 = 'o'; count = inputString.codePoints().filter(ch -> ch == searchChar2).count(); System.out.println("Character "+searchChar2+" appears in the inputString "+count+" times"); } }
Output:
Character a appears in the inputString 2 times
Character o appears in the inputString 3 times
4. Using Third-Party (External) Libraries
4.1 Using StringUtils class
We can use external libraries also. The easiest way to count the occurrence of Character in the string is by using commons.lang.StringUtils class countMatches() method.We need to add the following dependency to use StringUtils class in our code.
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.12.0</version> </dependency>
You can find the latest version on the Maven repository.
Let's now find out how many 'e' characters are present in the "Alive is Awesome" string literal.
import org.apache.commons.lang3.StringUtils; public class CountOccurencesOfCharacter5 { public static void main(String args[]) { int count = StringUtils.countMatches("Alive is Awesome", 'e'); System.out.println(count); } }
Output:
3
4.2 Using Guava Library
We can also use the guava library in counting chars. The following dependency needs to be added to the pom.xml:<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>31.0.1-jre</version> </dependency>
You can find the latest version of the Guava library on the Maven repository.
Let's find out how guava library helps us in counting chars:
import com.google.common.base.CharMatcher; public class CountOccurencesOfCharacter6 { public static void main(String args[]) { int count = CharMatcher.is('P').countIn("Be In Present"); System.out.println(count); } }
Output:
1
5. Using Spring
Yes, even Spring framework StringUtils class provides countOccurrencesOf() method to count chars in String. Please find the code below:import org.springframework.util.StringUtils; public class CountOccurencesOfCharacter7 { public static void main(String args[]) { int count = StringUtils.countOccurrencesOf("LoveYourself", "o"); System.out.println(count); } }
Output:
2
Please mention in the comments if you have your code on count occurrences of a character in String in java.