我需要知道同一类型的字符在一个字符串中有多少个。
我试过这个
String x ="(3+3)*(4-2)";
int a = x.indexOf( "(" );但这只给了我第一个指数
发布于 2013-09-06 07:07:25
似乎最好把它放在一个单独的函数中:
// accepts a string and a char to find the number of occurrences of
public static int get_count(String s, char c) {
int count = 0; // count initially 0
for (int i = 0; i < s.length(); i++) // loop through the whole string
if (s.charAt(i) == c)
count ++; // increment every time an occurrence happens
return count; // return the count in the end
}你可以这样称呼它:
System.out.println(get_count("(3+3)*(4-2)", '('));
// Output: 2发布于 2013-09-06 07:03:10
您可以使用循环并使用其他方法indexOf(int, int)。
String x ="(3+3)*(4-2)";
int a = x.indexOf( "(" );
while (a >= 0) {
System.out.println("Char '(' found at: "+a);
a = x.indexOf('(', a+1);
}发布于 2013-09-06 06:57:23
使用StringUtils.countMatches
StringUtils.countMatches(value,"(");或
public static int countMatches(String value, String valueToCount) {
if (value.isEmpty() || valueToCount.isEmpty()) {
return 0;
}
int count = 0;
int index = 0;
while ((index = value.indexOf(valueToCount, index)) != -1) {
count++;
index += valueToCount.length();
}
return count;
}https://stackoverflow.com/questions/18651704
复制相似问题