0

Counting word occurences in a string

I found there are 2 ways to count them, which are: 1) Using array and split() 2) Using int var and split() //second method String str = "i have a male cat. the color of male cat is Black"; int c = str.split("male cat").length - 1; im still confused on how the second method works. How does it really work?

26th Nov 2020, 5:45 AM
M.O.HONOR
M.O.HONOR - avatar
2 Réponses
+ 2
"i have a #. the color of # is Black" I just replaced male cat with # for convenience. Now when you split the string, you can see that it is split into 3 parts. One part before 1st # One part after 2nd # One part between 1st and 2nd # So the length()-1 will return 2 which the number of occurrence of the 'male cat'.
26th Nov 2020, 6:00 AM
Avinesh
Avinesh - avatar
+ 1
@Avinesh thank youuuu
26th Nov 2020, 6:23 AM
M.O.HONOR
M.O.HONOR - avatar