Question

I am trying to go through an array of Operators to see if one of the operators is located in the String.

For example:

String[] OPERATORS    = { "<", "<=", ... };
String line = "a <= b < c ";

How would I go about going through a loop that checks to see if an operator is in the string?

Also, say my method found that "<" is located in the string at "<= "

However, I am looking for the actual string " <= ". How would I go about accounting for that?

Was it helpful?

Solution

I would use a regex instead of having array of all the operators. Also, make sure the operators are in the exact order in your regex, i.e., <= should be before <, similarly, == should be before =:

String regex = "<=|<|>=|>|==|=|\\+|-";

String line = "a <= b < c ";

Matcher matcher = Pattern.compile(regex).matcher(line);

while (matcher.find()) {
    System.out.println(matcher.start() + " : " + matcher.group());
} 

Output:

2 : <=
7 : <

The trick is that, before the regex matches <, of <=, it will already be matched by <=, as it comes before <.

OTHER TIPS

Something like this should account for >= matching >.

String[] OPERATORS = {"<=>", "<=", ">=", ">", "=" ..} //The key here is that if op1 contains op2, then it should have a lower index than it

String copy = new String(line);

for(String op : OPERATORS)
{
    if(copy.contains(op))
    {
        copy = copy.replaceAll(op, "X"); //so that we don't match the same later
        System.out.println("found " + op);
    }
}

If you need the index as well, then when you need to replace OP with a number of X's that is the same length. If you can have multiples of each op and you need the position of all of them, then it's more work still. But the question isn't overly specific on that stuff. In any case, this should get you rolling.

Here is what I would do:

for(String operator : OPERATORS)
{
    if(Pattern.compile("[\\s\\w]" + operator + "[\\s\\w]").matcher(line).find())
    {
        System.out.println(operator + " found in " + line);
    }
}

It should work correctly in terms of not finding the < operator in <=.

Full code:

import java.util.regex.Pattern;

public class Test
{
    public static void main(String[] args)
    {
        String[] OPERATORS = { "<", "<="};
        String line = "a <= b < c ";

        for(String operator : OPERATORS)
        {
            if(Pattern.compile("[\\s\\w]" + operator + "[\\s\\w]").matcher(line).find())
            {
                System.out.println(operator + " found in " + line);
            }
        }
    }
}

This would work only if the operator has space in both side:

for (String operator : OPERATORS) {
    Matcher m = Pattern.compile("\\s\\" + operator + "\\s").matcher(line);
    while (m.find())
         System.out.println((m.start() + 1) + " : " + m.group());
}

and this works without any special ordering of the operators.

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