How to count the occurrences of a character in Java – Three Better Ways
There are three ways.
- Using charAt – Traditional For Loop
- Using toCharArray – Enhanced For Loop
- Using replaceAll – Efficient Way without Looping
NO 1 Using charAt – Tutorial
package com.javaindetail.PatternTutorial;
public class repeatedCharacters {
public static void main(String args[]){
String str = "javaindetail.com";
int counter = 0;
for( int i=0; i<str.length(); i++ ) {
if( str.charAt(i) == 'a' ) {
counter++;
}
}
System.out.println(counter);
}
}
NO 2 Using toCharArray – Tutorial
package com.javaindetail.PatternTutorial;
public class repeatedCharacters {
public static void main(String args[]){
String str = "javaindetail.com";
int counter = 0;
for(char c : str.toCharArray()) {
if( c == 'a' ) {
counter++;
}
}
System.out.println(counter);
}
}
NO 3 Using replaceAll – Tutorial
package com.javaindetail.PatternTutorial;
public class repeatedCharacters {
public static void main(String args[]){
String str = "javaindetail.com";
int counter = str.length() - str.replaceAll("a", "").length();
System.out.println(counter);
}
}
Enjoy Reading This Article?
Here are some more articles you might like to read next: