简体   繁体   中英

Check if index is within parentheses

I'm trying to create a method in Java that checks if an index of a String is contained inside parentheses. Currently I'm just checking if ) or ( comes first, but it doesn't work well for nested parentheses.

private static boolean inParentheses(String str, int index) {
    int nextOpen = str.indexOf('(', index);
    int nextClose = str.indexOf(')', index);
    return nextClose < nextOpen && nextOpen != -1 || nextOpen == -1 && nextClose != -1;
}

So you want to first check what the first character of the string is. Lets say you have string ipwnmice and you wanted to see if it had the character ( or the character ) at the very front of it.

String yourUsername = "ipwnmice"; 
char first = yourUsername.charAt(0);
System.out.println(first);

output:

i

Now, if you want to see whether the first character is ( or ) just add an if statement around the code!

 String parenthasis = "(Hello)"
 char first = parenthasis.charAt(0);

if(first.equals("()){
//CONTAINS ( OR ) AS FIRST CHARACTER
} else{
//DOESNT CONTAIN ( OR ) AS FIRST CHARACTER
}

It might not be in the beginning of the string:

Use the .contains() method.

if(String.contains( ( || ) ){

}

That's it. Get the character of the first letter of the string, and check if it contains ( or ) . If you found this answer useful, mark it best answer. If you need any more help, feel free to ask, I am happy to help.

{Rich}

If you can safely assume that the parenthesis are all closed properly, then it amounts to counting the number of open and closed parenthesis to one side of your index. If they equal out you are not in parenthesis, otherwise you are. Be wary of the answer when your index references a parenthesis though.

int open_par = 0;
for(int i=index;i--!=0;){
   if(str.charAt(i)=='(')
      open_par++; //count open parenthesis
   if(str.charAt(i)==')')
      open_par--; //count closed parenthesis
}
return open_par>0; //if open parenthesis exceeds closed parenthesis

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM