We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 7
oart2023 20:35, Count Occurrences of a Char ina String | Baeldung
“
Count Occurrences of a Char in a String
RILGLL’
‘Spine ~ Australas tech pow
Sr Soy
httos //adsfreestarcom/?
Last updated: August 22,2023
\Written by. baeldung (https //wwwlbaeldung.com/author/oae\dung)
Java String (https:// www.baeldung.com/category/java/java-string)
Java Characters thttps://wwa:baeldung.com/tag/java-characters)
Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:
>» CHECK OUT THE COURSE (/Is-course-start)
hitpsilwwwbaeldung.convjava-count-chars weoart2023 20:35, Count Occurrences of a Char ina String | Baeldung
y thttps//ads freestaccom/?
Lutm_campaign-branding&uutm-medium-banner&utm source-baeldung.com&utm.content-baeldung.incontent
=)
1, Overview
There are many ways to count the number of occurrences of a char ina String in Java
In this quick tutorial, well focus on a few examples of how to count characters — first with the core Java library and
then with other libraries and frameworks such as Spring and Guava.
Further reading:
Using indexOf to Find All Occurrences of a Word in a String (/java-indexof-find-
string-occurrences)
Learn how to solve the ‘needle ina haystack’ problem by using the incexOf method to find all occurrences of a word in
a larger text sting.
Read more (/java-indexof-fnd-string-occurrences) —-
Guava CharMatcher (/guava-string-charmatcher)
Use the Guava CharMatcherto work with Strings - remove spe
armong other super useful API,
3 chars, validate, trim. collapse, replace and count
Read more (/quava-string-charmatcher) —-
String Processing with Apache Commons Lang 3 (/string-processing-commons-
lang)
‘Quick intro to working with Strings with the Apache Commons library and StringUtls
Road more (/string-processing-commons-lang) —>
2. Using Core Java Lib
2.1, Imperative Approach
Some developers may prefer to use core Java. There are many ways for counting the number of accurrences of a
char ina String.
Lets start with a simple/naive approach:
‘elephant; oO
String sonestring
car sonechar
Sat couns = 95
For (int 4 = 0; 4 < somestes
HF (Sonestring.charae(i)
‘sonechar)
>
,
assertequals(2, count);
Not surprisingly this will work, but there are better ways t
hitpsilwwwbaeldung.convjava-count-chars ano4r112023 20:35 Count Occurrences of a Char ina Strng | Baeldung
= BoC)
Optimisation des charges de travail
Optimisation des
charges de travail SAP SAP avec le cloud
avec le cloud
a
thitps/ads freestarcom/?
2.2, Using Recursion
less obvious but stillinteresting solution is to use recursion
private static int useRecursiont
String sonesteing, char searchedChar, Ant index) {
4f (index > someString. length) {
return 8;
)
Ant count = soneString-charAt(index) == searehedchar 7 1 + 0)
return count + useRecursient
Ssonestring, searchedChar, index + 1)5
\We can invoke this recursive method in the following way: useRecursionToCountChars(‘elephant’ ' 0}
2.3. Using Regular Expressions
Another way would be to use regular expressions:
Pattern patter
Watcher matcher
Sat count = 9;
write (nateher Find)
Pattern. compste(*(telo")
pattern matcher (“elephant
y
assertequals(2, count);
Just note that this solution is technically correct but sub-optimal. as its overkill to use the very powerful regular
‘expressions to solve such a simple problem as finding the number of occurrences of a character in a string.
2.4. Using Java 8 Features
New features available in Java 8 can be very helpful here.
Cy
eam how fo prepare fortis
change
vat
. (https /ads freestarcom/?
tipsufmaew-baeldung.comijava-count-chars
ano4r112023 20:35 Count Occurrences of a Char ina Strng | Baeldung
Lots use stro-ms and lambdas tp implement the count:
‘Long count = someString-chars().filter(ch -> ch ) count () 5 0
‘erg count2 = somestring.codePoints() filter (ch => ch ==
assertequals(2, count2);
Ye") counts
So. this is clearly a cleaner and more readable solution using the core library
3. Using External Libraries
Lets now look at a few solutions that make use of utities from external libraries
34, Using StringUtils
In general, itis always better to use an existing solution instead of inventing our own. The
‘commons lang.StringUiti’s class provides us with the countMatches method, which can be used for counting
‘chars or even sub-strings in given String.
First, we need to include the appropriate dependency,
org.apache.comons
comons-lang3
everstor>3.12.8¢/version>
«Ieependency>
\We can find the latest version on Maven Central
{https://searchmaven org/classic/#search’%7Cga%7C1%7Cq%3A%220rg.apache commons%22%20AND%203%3A%
zacommons-lang3%22).
Lets now use countMatches0 to count the number of e characters in the 'elephant” String literal
Jat count = stringutis.counthatches(“eLephan
assertequals(2, court);
0
3.2, Using Guava
Guava can also be helpfulin counting chars, We need to define the dependency:
nto
“practice poghepnarots 0
Sriram iottarctaco
Sealers jensen
ssoroicey
tipsufmaew-baeldung.comijava-count-charso4r112023 20:35 Count Occurrences of a Char ina Strng | Baeldung
‘We can find te latest version on aven Central
{hiiys://searchmaven org/> CHECK OUT THE COURSE (/1s-course-end)
tipsufmaew-baeldung.comijava-count-chars sro4r112023 20:35 Count Occurrences of a Char ina Strng | Baeldung
Learning to build your API
with Spring?
Download the E-book (/rest-api-spring-guide)
Comments are closed on this article!
‘couRSES
SERIES
JACKSON JSON TUTORIAL /3HCxSON)
SPRING PERSISTENCE TUTORIAL V/PERSISTENCS.ATHSPING-SERIES)
‘ABOUT
htipsifwnewcbaeldung,comjava-count-charsoart0es 2035
Taeruaccim vrata ancl?
tipsufmaew-baeldung.comijava-count-chars
Count Occurrences of a Char ina Strng | Baclsung
W