简体   繁体   English

检查索引是否在括号内

[英]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. 我正在尝试在Java中创建一个方法来检查括号内是否包含String的索引。 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. 假设您有字符串ipwnmice并且想查看它的ipwnmice是否包含字符(或character )

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! 现在,如果要查看第一个字符是否为()只需在代码周围添加一条if语句!

 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. 使用.contains()方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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