【问题标题】:See if String Contains An Element in an Array查看字符串是否包含数组中的元素
【发布时间】:2014-03-26 16:52:07
【问题描述】:

我正在尝试通过一组运算符来查看其中一个运算符是否位于字符串中。

例如:

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

我将如何通过一个循环来检查一个运算符是否在字符串中?

另外,假设我的方法发现“=”

但是,我正在寻找实际的字符串“”。 我将如何进行会计处理?

【问题讨论】:

  • 试试这个line.contains(OPERATORS[index])
  • 你可以使用正则表达式来匹配特定的运算符
  • 你可以使用 Apache StringUtils#containsOnly。

标签: java arrays string element contain


【解决方案1】:

我会使用正则表达式而不是所有运算符的数组。此外,请确保运算符在您的正则表达式中的顺序准确,即&lt;= 应该在&lt; 之前,同样,== 应该在= 之前:

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

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

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

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

输出

2 : <=
7 : <

诀窍在于,在正则表达式匹配&lt;= 中的&lt; 之前,它已经与&lt;= 匹配,因为它在&lt; 之前。

【讨论】:

  • +1,使用与我相同的技巧,但使用这样的正则表达式要好得多。
【解决方案2】:

这样的事情应该说明 >= 匹配 >。

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);
    }
}

如果您还需要索引,那么当您需要将 OP 替换为相同长度的多个 X 时。如果您可以拥有每个操作的倍数并且您需要所有操作的位置,那么它仍然需要更多的工作。但是这个问题并没有过于具体。无论如何,这应该让你滚动。

【讨论】:

    【解决方案3】:

    我会这样做:

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

    就在&lt;= 中找不到&lt; 运算符而言,它应该可以正常工作。

    完整代码:

    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);
                }
            }
        }
    }
    

    【讨论】:

    • 使用你的方法,一旦找到“,它仍然会停止
    【解决方案4】:

    这只有在操作符两边都有空格时才有效:

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

    这无需对运算符进行任何特殊排序即可工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-22
      • 2013-10-03
      • 1970-01-01
      • 2016-09-22
      • 2011-12-23
      • 2013-09-27
      • 2016-06-17
      • 2023-03-13
      相关资源
      最近更新 更多