0
I have a text and I want to pick up the starting positions of a specific word in all occurrences within that text. For example, I have the following text:
maria gosta de joão. jose gosta de maria. maria gosta de joao e jose.
Note that the word "maria" has 3 occurrences. If I used indexOf("maria")
, the result would be 0
, because the indexOf
takes only the first instance. Only indexOf
does not take the position of all occurrences, only the first and last with lastIndexOf
.
What I wanted was to get the position of the 3 words "mary", which in the above text would be:
maria gosta de joão. jose gosta de maria. maria gosta de joao e jose.
↑ ↑ ↑
0 35 42
I could do this by going through the text, character by character, but if the text is too long, I don’t see a good way.
What efficient or better technique could I use to get this result? Maybe a regex?
you want to avoid the loop with substring?
– Leandro Angelo
I preferred because if the text is too large, it is half Abajara. You can even use a loop at some point, but wanted a more efficient way.
– Sam