如何计算字符串中的括号?

How do I count the parentheses in a string?

这是我计算字符串中括号数量的方法。

public int checkParenthesis(String print, char par){
    int num = 0;
    for(int i = 0; i<print.length(); i++){
        if(print.indexOf(i) == par){
            num++;
        }
    }
    return num;
}

没用。它 returns 0。 print是随机字符串,par是括号。

你需要使用.charAt获取当前字符并与par进行比较:

if(print.charAt(i) == par)

另一种方法:

for(char c : print.toCharArray()) {
  if(c == par) {
    num++;
  }
}

你的意思是 charAt 而不是 indexOf

不同之处在于,charAt 占据字符串中的一个位置 (0, 1, ...) 而 returns 该位置的字符。 indexOf 获取一个字符,并在字符串中搜索找到该字符的第一个位置。您将 int 传递给 indexOf,而不是 char,但编译器接受此“感谢”隐式转换。

在java中indexOf用于检查索引处的ch。您可以使用 string.charAt(index) 而不是 indexOf 来获得所需的结果。

public int checkParenthesis(String print, char par){
    int num = 0;
    for(int i = 0; i<print.length(); i++){
        if(print.charAt(i) == par){
            num++;
        }
    }
    return num;
}

正如其他人所指出的,您当前的算法正在使用循环检查每个索引处的字符。这适用于 String.charAt(int) 但不适用于 String.indexOf(int)。但是,您当然可以使用 String.indexOf(int, int) 来实现它。此外,我更喜欢抢先检查 null 和空输入。最后,您的方法计算匹配字符(不是“检查括号”)并且不依赖于 class 状态,因此我将其设为 static。像,

public static int countChar(String print, char par) {
    if (print == null || print.isEmpty()) {
        return 0;
    }
    int num = 0;
    int pos = -1;
    while ((pos = print.indexOf(par, pos + 1)) != -1) {
        num++;
    }
    return num;
}

另一种方式,但创建额外的 String 对象:

 int cnt=print.length()-print.replaceAll(String.valueOf(c),"").length();

因为 Java 9 你可以使用 String#codePoints 方法:

static long characterCount(String str, char ch) {
    // filter the desired characters and return their quantity
    return str.codePoints().filter(cp -> cp == ch).count();
}
public static void main(String[] args) {
    System.out.println(characterCount("srting))", ')')); // 2
    System.out.println(characterCount("{srting}", '{')); // 1
    System.out.println(characterCount("(srting)", 's')); // 1
    System.out.println(characterCount("[srting]", 'ё')); // 0
}

另请参阅:Recursive method that returns true if the integer exists only once in an array