Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I count the parentheses in a string?

Tags:

java

string

char

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.

like image 233
Michelle Avatar asked Feb 21 '21 17:02

Michelle


People also ask

How do I count parentheses in C++?

Inside the loop, set str as paran[i] i.e. the first element of parentheses and again calculate the length of a string. Inside the loop, check IF str[j] = '(' then increment the first by 1 ELSE check IF first = 1 then decrement the first by 1 ELSE increment the last by 1.

How do you check if a given string contains valid parentheses?

Push an opening parenthesis on top of the stack. In case of a closing bracket, check if the stack is empty. If not, pop in a closing parenthesis if the top of the stack contains the corresponding opening parenthesis. If the parentheses are valid,​ then the stack will be empty once the input string finishes.

How do you balance parentheses?

For the parentheses to be balanced, each open parenthesis must have a corresponding close parenthesis, in the correct order. For example: ((())) is balanced. (()(()())) is balanced.


Video Answer


1 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++;
  }
}
like image 102
Majed Badawi Avatar answered Sep 20 '22 19:09

Majed Badawi