Java - number of characters per line

Let's say I have this line:

String helloWorld = "One,Two,Three,Four!"; 

How can I do this to count the number of commas in String helloWorld ?

+7
source share
5 answers

The easiest way is to loop over 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!"); 
+18
source
 int numberOfCommas = helloWorld .replaceAll("[^,]","").length(); 

You can find more implementation in this site.

+6
source
 String[] tokens = helloWorld.split(","); System.out.println("Number of commas: " + (tokens.length - 1)); 
+4
source

Not so simple, but shorter.

 String str = "One,Two,Three,Four!"; int num = str.replaceAll("[^,]","").length(); 
+1
source

If you can import com.lakota.utils.StringUtils then it's that simple. Import this> import com.lakota.utils.StringUtils;

 int count = StringUtils.countMatches("One,Two,Three,Four!", ","); System.out.println("total comma "+ count); 
-one
source

All Articles