Question

public enum OPERATORS {
  MUL("*"), ADD("+"), SUB("-"), DIV("/")
}

and a String as

s = A2 B4 * C5 /

How can I check if s has one of the OPERATORS?

No correct solution

OTHER TIPS

Assuming getOperatorSymbol() is implemented in your enum

for (OPERATORS op: OPERATORS.values()) {
  if(s.contains(op.getOperatorSymbol())
  {
      //your code
  }

}

How can I check if s has one of the OPERATORS?

You have to code it somehow. The strings you are searching for are not the names of the enum value. They are stored in a custom attribute. So you have to manually extract the strings and then search in the target string for each one.

There are multiple of ways you could do this; e.g.

  • You could simply loop over the OPERATOR enum values, extract each one's operator string and test it against your input string; see @pangea's Answer.

  • You could use the loop to build a regex that would match any of the operator strings and then use that regex to match the string. This would be a good approach if performance is a real concern and you can amortize the cost of creating the regex; i.e. do it just once, and reuse the regex multiple times. (But if performance is not a concern, the extra complexity of this approach is not warranted.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top