EN
Java - count character occurrences
0 points
In this article, we would like to show you how to count occurrences of a character in a String in Java.
Quick solution:
xxxxxxxxxx
1
String text = "ABC";
2
char character = 'A';
3
int result = 0;
4
5
for (int i = 0; i < text.length(); i++) {
6
if (text.charAt(i) == character) {
7
result++;
8
}
9
}
10
11
System.out.println(result); // 1
In this example, we create simple for loop to iterate through the string and check if each character matches the character
we want.
xxxxxxxxxx
1
public class Example {
2
3
public static void main(String[] args) {
4
String text = "ABA";
5
char character = 'A';
6
int result = 0;
7
8
for (int i = 0; i < text.length(); i++) {
9
if (text.charAt(i) == character) {
10
result++;
11
}
12
}
13
14
System.out.println("result = " + result); // 2
15
}
16
}
Output:
xxxxxxxxxx
1
result = 2
In this example, we use String replace()
method with string length subtraction to count the occurrences of the A
character in the text
.
xxxxxxxxxx
1
public class Example {
2
3
public static void main(String[] args) {
4
String text = "ABA";
5
int result = text.length() - text.replace("A", "").length();
6
7
System.out.println("result = " + result); // 2
8
}
9
}
Output:
xxxxxxxxxx
1
result = 2
In this example, we use String replace()
method with [^A]
regex to count the occurrences of the A
character in the text
.
Regex explanation:
[^ ]
is the negation operator, negated set (matches any character that is not in the set),[^A]
matches any character except A.
Practical example:
xxxxxxxxxx
1
public class Example {
2
3
public static void main(String[] args) {
4
String text = "ABA";
5
int result = text.replaceAll("[^A]", "").length();
6
7
System.out.println("result = " + result); // 2
8
}
9
}
Output:
xxxxxxxxxx
1
result = 2
In this example, we use String split()
method with string length()
to count the occurrences of the A
character in the text
.
xxxxxxxxxx
1
public class Example {
2
3
public static void main(String[] args) {
4
String text = "ABA";
5
int result = text.split("A", -1).length - 1;
6
7
System.out.println("result = " + result); // 2
8
}
9
}
Output:
xxxxxxxxxx
1
result = 2