Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 271
Khushboo Chaudhary Avatar asked Jul 17 '26 00:07

Khushboo Chaudhary


1 Answers

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

System.out.println(str.split("that", -1).length-1);
like image 166
Reimeus Avatar answered Jul 18 '26 15:07

Reimeus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!