February 9th, 2012, 03:25 PM
Number of occurrences in a String
I'm working on a very basic String program, where I am counting the number of occurrences of a single character within a string (i.e. the count the number of "a"s in "Java is an interesting language").
As of right now, I'm substring'ing it up. However, I looked back over my assignment requirements and apparently we're supposed to use String.indexOf() to determine the number of occurrences. When I looked at the docs, I thought... what? This only returns an index.
How can I go about determining the number of occurrences of a single char within a string with indexOf? For whatever reason, it's not clicking with me. Any help is appreciated.
February 9th, 2012, 05:35 PM
Look at the API doc for the indexOf method. There is more than one version.
A usage: Find the first, find the next, continue finding the next until there are no more. Count them as you find them.
February 9th, 2012, 11:43 PM
IndexOf is an interesting way to parse a string. You will need to run it in a while or do while loop with a sentinel marking the end of the string you are reading. indexOf returns -1 automatically when a character isn't found. So, you can use that as your sentinel.
You can use the following indexOf:
indexOf(int ch, int fromIndex)
Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
So, what you would do is let indexOf return the index of the first 'a', increment your counter and use the index returned + 1 to send an indexOf message again. The reason you increment the index by 1 is because otherwise you would be finding the same character over and over (infinite loop). A recursive solution would be interesting to see.
Hope that helps.
Edit: I wrote a recursive and iterative solution to this problem. If you are having more trouble I can post up some pseudocode for ya if that would help.