0

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
Peter
  • 68
  • 9

1 Answers1

0

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

Helam
  • 1,385
  • 13
  • 17
  • Ah yes, this is called a ["fencepost error"](https://en.wikipedia.org/wiki/Off-by-one_error#Fencepost_error) – Alexander Mar 09 '20 at 18:41