Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Count number of symbols in string

Tags:

java

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?

like image 412
test Avatar asked Feb 23 '11 23:02

test


2 Answers

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!");
like image 110
corsiKa Avatar answered Nov 02 '22 06:11

corsiKa


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);
like image 41
Mahfuz Ahmed Avatar answered Nov 02 '22 07:11

Mahfuz Ahmed