How do I count the parentheses in a string?

Viewed 216

This is my method to count the number of 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;
}

It doesn't work. It returns 0. print is a random string and par is a parenthesis.

6 Answers

You need to use .charAt to get the current character and compare it with par:

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

Another way to do this:

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

You meant charAt instead of indexOf.

The difference is that charAt takes a position in the string (0, 1, ...) and returns the character at that position. indexOf takes a character, and searches the string for the first position where that character is found. You're passing an int to indexOf, not a char, but the compiler accepts this "thanks" to implicit conversions.

In java indexOf is used for checking ch at index. Instead of indexOf u can use string.charAt(index) to get desired result.

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;
}

As others have pointed out, your current algorithm is examining characters at each index with a loop. That would be appropriate with String.charAt(int) but not String.indexOf(int). However, you could certainly implement it with String.indexOf(int, int). Also, I prefer to check for null and an empty input preemptively. Finally, your method counts matching characters (not "checking parenthesis") and doesn't depend on class state so I would make it static. Something like,

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;
}

Since Java 9 you can use String#codePoints method:

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
}

See also: Recursive method that returns true if the integer exists only once in an array

Just one another way, but with creating extra String objects:

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