[英]Splitting up a boolean expression in Java
How can I split a boolean expression in Java? 如何在Java中拆分布尔表达式? For example, I want to get the following from the expression
a_1 & b_2 | (!c_3)
例如,我想从表达式
a_1 & b_2 | (!c_3)
获取以下内容 a_1 & b_2 | (!c_3)
: a_1 & b_2 | (!c_3)
:
String tokens[] = {"a_1", "&", "b_2", "|", "(", "!", "c_3", ")"};
The names of the variables contain alphanumeric characters and underscores ( _
). 变量的名称包含字母数字字符和下划线(
_
)。
If you want to parse the String - maybe to create a syntax tree and evaluate the expression -, then it's better to parse the String with a simple switch expression: 如果要解析String - 可能要创建语法树并计算表达式 - 那么最好用简单的switch表达式解析String:
// for each char c in String
switch (c) {
case '&': processAnd();break;
case '|': processOr();break;
case '!': processNot();break;
case '(': processOpenPara();break;
case ')': processClosePara();break;
case ' ': break;
default: processVarName(); break;
}
This is just a stub to show the pattern. 这只是一个显示模式的存根。 You may want to use a stack to evaluate the expression.
您可能希望使用堆栈来评估表达式。
If you have 如果你有
String str = "a & b | (!c)";
first, get rid of spaces: 首先,摆脱空间:
String str2 = str.replaceAll(" ", "");
then, obtain the array you want like this: 然后,获取你想要的数组:
String[] array = str2.split("");
Update : based on OP's changed question, another solution follows: 更新 :基于OP改变的问题,另一个解决方案如下:
String str = "a_1 & b_2 | (!c_3)"; // initial string
StringCharacterIterator sci = new StringCharacterIterator(str); // we use a string iterator for iterating over each character
List<String> strings = new ArrayList<String>(); // this will be our array of strings in the end
StringBuilder sb = new StringBuilder(); // a string builder for efficiency
for(char c = sci.first(); c != sci.DONE; c = sci.next()) {
if( c == ' ' ) {
continue; // we ignore empty spaces
}
else if(
c == '&' ||
c == '(' ||
c == ')' ||
c == '|' ||
c == '!')
{
// if we stumble upon one of 'tokens', we first add any previous strings that are variables to our string array, then add the token and finally clean our StringBuilder
if(sb.length() != 0) strings.add(sb.toString());
strings.add(String.valueOf(c));
sb = new StringBuilder();
}
else {
sb.append(c); // we have a character that's part of a variable
}
}
String[] finalArray = strings.toArray(new String[0]); // we turn our list to an array
for (String string : finalArray) {
System.out.println(string); // prints out everything in our array
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.