Search code examples
javasplit-function

Split a String using split function to count number of "that"


String str = "ABthatCDthatBHthatIOthatoo";     
System.out.println(str.split("that").length-1);

From this I got 4. that is right but if last that doesn't have any letter after it then it shows wrong answer '3' as in :

String str = "ABthatCDthatBHthatIOthat";
System.out.println(str.split("that").length-1);

I want to count the occurrence of "that" word in given String.


Solution

  • You could specify a limit to account for the final 'empty' token

    System.out.println(str.split("that", -1).length-1);