Let's say I have this string:
String helloWorld = "One,Two,Three,Four!";
How can I make it so it counts the number of commas in String helloWorld
?
the simplest way would be iterate through the String and count them.
int commas = 0;
for(int i = 0; i < helloWorld.length(); i++) {
if(helloWorld.charAt(i) == ',') commas++;
}
System.out.println(helloWorld + " has " + commas + " commas!");
If you can import com.lakota.utils.StringUtils then it's so simple. Import this> import com.lakota.utils.StringUtils;
int count = StringUtils.countMatches("One,Two,Three,Four!", ",");
System.out.println("total comma "+ count);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With