Reputation: 3
I have a string similar to this ,,,foo,bar
and I need to count the amount of "," at the beginning of the string in java any ideas?
Upvotes: 0
Views: 370
Reputation: 31182
You can also use regexp:
public static int countCommasAtBegin(String str) {
Matcher commas = Pattern.compile("^,*").matcher(str);
if (commas.find()) {
return commas.group().length();
} else {
return 0;
}
}
but for such trivial task I prefer to use simple loop.
Upvotes: 0
Reputation: 31182
If you don't want to use any any external jars just write a simple function:
public static int countAtBegin(String str, char c) {
for (int ret = 0; ret < str.length(); ret++) {
if (str.charAt(ret) != c)
return ret;
}
return str.length();
}
Upvotes: 0
Reputation: 393
This quick-n-dirty solution worked for me.
public static void main(String[] args)
{
String s = ",,,foo,bar";
int count = 0;
for (int i = 0; i < s.length() ; i++) {
if (s.charAt(i) != ',')
break;
count++;
}
System.out.println("count " + count);
}
Update: just realized that you only need to count the ',' at the beginning of the string and not the middle. I've updated the code to do that.
Upvotes: 0
Reputation: 7692
If starting characters are known then build a regex pattern and get the first group. First group string will contain the exact match of desired sequence, length of this string is the resultant count.
Upvotes: 1
Reputation: 274612
Take a look at the String javadoc. It contains methods you can use to get the length of the String and get characters at certain positions.
Upvotes: 1
Reputation: 14053
A simple loop (while or for) containing a if with a condition of equality that increments a counter if true should be enough.
Upvotes: 0
Reputation: 36456
Have a counter
variable which counts the number of occurrences. Then loop through the entire String
, using charAt(i)
to get the char
at position i
. Test to see if it's equal to charAt(0)
. If it is, increment counter
and if it isn't, break
out of the loop.
Upvotes: 2