多个字符串比较的简写(或更短的语法)

时间:2013-06-16 21:19:44

标签: java

如果我想查看一个子字符串是否等于其他几个子字符串中的任何一个。如果不将每个案例放在一起,可以做到这一点:

目前的方式:

if ( substr.equals("move") || substr.equals("mv") || substr.equals("mov") ){…}

更短的版本(不工作):

if ( substr.equals("move" || "mv" || "mov") )

6 个答案:

答案 0 :(得分:8)

将所有字符串放在Set<String>中并使用contains方法。

例如:

private final Set<String> wordMoveTokens = new HashSet<String>(Arrays.asList("move", "mv", "moov"));
...
// substr = "move"
if (wordMoveTokens.contains(substr) ) {
   .... // True
}

查看here了解更多示例。

答案 1 :(得分:4)

我至少可以想到3种不同的方法:

  1. 使用Set<String>保存所有可能的匹配项,并在if statmeent中使用Set<String>.contains()

  2. 如果您使用的是JDK 1.7,则可以使用switch语句:

    switch (substr) {
        case "move":
        case "mv":
        case "mov":
            // ...
            break;
    }
    
  3. 使用正则表达式:

    if (substr.matches("move|mov|mv") {
        //...
    }
    

答案 2 :(得分:3)

你可以试试这种方式

substr.matches("move|mv|mov");

但请注意$^+*,{{1}}等。{/ p>

答案 3 :(得分:2)

您可以使用:

if ((Arrays.asList("move","mov","mv")).contains(substr))

答案 4 :(得分:1)

尝试:

private static final Set<String> SUBSTRINGS = new HashSet<>(Arrays.asList("move", "mv", "mov"));

...

SUBSTRINGS.contains(substr);

答案 5 :(得分:1)

在原生JDK中,没有。

但是有很多可能性。如果您使用Set

,则有一种快捷方式
// Written with Guava, I'm too lazy
final Set<String> moves = ImmutableSet.of("move", "mv", "mov");
moves.contains(substr); // true if there is a match

或自定义功能:

public boolean matchesOneOf(String whatToMatch, String... candidates)
{
    for (final String s: candidates)
        if (whatToMatch.equals(s))
            return true;
    return false;
}

现在,这一切都取决于您的数据。你最好的选择是有效地构建它,以便你必须做你目前做的事情;)

相关问题