1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2012
    Rep Power

    Number of occurrences in a String

    Hello all,

    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.
  2. #2
  3. Contributing User
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Aug 2010
    Eastern Florida
    Rep Power
    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.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2012
    Rep Power
    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.

    Cheers, Cam.

    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.

IMN logo majestic logo threadwatch logo seochat tools logo