Search code examples
swiftswift3

Swift count how many of same word in a string


I want to be able to count how many times a word/phrase exists in a string.

I am trying:

 let counter =  htmlString.components(separatedBy:"href=\"/user/")

But it is giving me 11 when there is just 10 on the page.

I am getting them from here via the source code. I am not using the .json way as I need to get the avatar urls etc.

https://www.reddit.com/r/pics/about/moderators

Solution

  • Getting 11 makes sense.

    Think about this example:

    "ababa".components(separatedBy: "b")
    

    If you split the string everywhere a "b" occurs, you'll get 3 strings that are all "a", so you have to subtract 1 to get the answer you want: 2.

    This works even if there are not other characters between what you are looking for:

    "bb".components(separatedBy: "b")
    

    The above code returns 3 empty strings, so you cant still take the count and subtract 1 to get the number you want.

    Also see similar question with relevant answers: Number of occurrences of substring in string in Swift