Link to home
Start Free TrialLog in
Avatar of priyavrat
priyavrat

asked on

How to count occurences of a char in string?

Hi
Is there any api for counting occurences  of
a character in a string.
Eg, My string is "2-3-4-5"
and i want to know the number of times "-"
appeared in the string

I know its simple but is there any api for it?
Thanks
Priyavrat
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of TheSailor
TheSailor

I think "while(*s)if(*s=='-')n++;" is just too simple to have an API for it.
Sorry, that should be "while(*s)if(*s++=='-')n++;"
oops, thats not java, sorry
LOL :-D
Avatar of priyavrat

ASKER

there is nothing to LOL TimYates
Thanks buddy.
I'm new to Java but anyway thanks again
Soz fella, I was LOL at the cool code TheSailor put in :-)

I wish we could do that in java sometimes...there should be something like:

  int n = 0 ;
  String s = "2-3-4-5" ;

  pointeraware {
    while(*s)if(*s++=='-')n++;
  }

Or summat...

Wasn't laughing at you... :-/