Languages
[Edit]
EN

Java - count character occurrences

0 points
Created by:
Huzaifa-Ball
475

In this article, we would like to show you how to count occurrences of a character in a String in Java.

Quick solution:

 

1. Using simple for loop

Edit

In this example, we create simple for loop to iterate through the string and check if each character matches the character we want.

Output:

2. Using String replace()

Edit

In this example, we use String replace() method with string length subtraction to count the occurrences of the A character in the text.

Output:

3. Using String replaceAll()

Edit

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:

Output:

4. Using String split()

Edit

In this example, we use String split() method with string length() to count the occurrences of the A character in the text.

Output:

Alternative titles

  1. Java - count character occurrences in string
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java - String (popular problems)

Java - count character occurrences
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join