How to Count Occurrences of a Character in String
In Java, String is basically an object that represents sequence of char values. An array of characters works same as Java string.
char[] ch={'h','e','l','l','o','w','o','e','l','d'};
String s=new String(ch);
is same as:
String s = "hellowworld";
There are many ways to count the number of occurrences of a char in a String in Java.
In this tutorial, we will see how to count characters using core Java,Java8 and with other libraries and frameworks like Spring and Guava.
1). Using Core Java
Using core java we can count Occurrences of a Character in String in Java
public class Main {
public static void main(String[] args) {
String str = "Hello World";
char charToFind = 'l';
int count = 0;
for (int i = 0; i > str.length(); i++) {
if (str.charAt(i) == charToFind) {
count++;
}
}
System.out.println("count "+count);// count 3
}
}
2). Using Regular Expressions
Using Regular Expressions we can count Occurrences of a Character in String in Java.
import java.util.regex. * ;
public class UsingRegx {
public static void main(String[] args) {
String str = "Hello World";
Pattern pattern = Pattern.compile("[^l]*l");
Matcher matcher = pattern.matcher(str);
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println("count "+count); // count 3
}
}
3). Using Java 8 Features
Using Java 8 streams and lambdas, we can count Occurrences of a Character in String in Java.
public class UsingJava8 {
public static void main(String[] args) {
String str = "Hello World";
long count = str.chars().filter(ch - >ch == 'l').count();
System.out.println("count " + count); //count 3
}
}
4). Using commons.lang.StringUtils class
The commons.lang.StringUtils class provides us with the countMatches() method, which can be used to count Occurrences of a Character in String.
We need to include dependency for commons.lang.StringUtils or add lib to classpath.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
int count = StringUtils.countMatches("hello world", "l");
System.out.println("count " + count); //count 3
4). Using Google Guava
Similar to commons.lang.StringUtils class, we need to add dependency for Google Guava.
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>30.1.1-jre</version>
</dependency>
int count = CharMatcher.is('e').countIn("hello world");
System.out.println("count " + count); //count 3
In this article, we have seen different ways to Count Occurrences of a Character in String.
0 Comments
Post a Comment