Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting a certain character in a String (Java)

Tags:

java

string

String a="(Yeahhhh) I have finally made it to the (top)";

Given above String, there are 4 of '(' and ')' altogether.

My idea of counting that is by utilizing String.charAt method. However, this method is rather slow as I have to perform this counting for each string for at least 10000 times due to the nature of my project.

Anyone has any better idea or suggestion than using .chartAt method?????

Sorry for not explaining clearly earlier on, what I meant for the 10000 times is for the 10000 sentences to be analyzed which is the above String a as only one sentence.

like image 375
Mr CooL Avatar asked Jul 11 '26 21:07

Mr CooL


2 Answers

StringUtils.countMatches(wholeString, searchedString) (from commons-lang)

searchedString may be one-char - "("

It (as noted in the comments) is calling charAt(..) multiple times. However, what is the complexity? Well, its O(n) - charAt(..) has complexity O(1), so I don't understand why do you find it slow.

like image 66
Bozho Avatar answered Jul 14 '26 10:07

Bozho


Sounds like homework, so I'll try to keep it at the "nudge in the right direction".

What if you removed all characters NOT the character you are looking for, and look at the length of that string?

There is a String method that will help you with this.

like image 21
MarkPowell Avatar answered Jul 14 '26 09:07

MarkPowell