IfElse或正则表达式

时间:2012-04-16 12:50:51

标签: android regex if-statement

当你有很长的IfElse时,哪一个是最好的方法?

        if (text.contains("text"))
        {
            // do the thing
        }
        else if (text.contains("foo"))
        {
            // do the thing
        }
        else if (text.contains("bar"))
        {
            // do the thing
        }else ...

或者

        if (text.contains("text") || text.contains("foo") || ...)
        {
            // do the thing
        }

或者

        Pattern pattern = Pattern.compile("(text)|(foo)|(bar)|...");
        Matcher matcher = pattern.matcher(text);
        if(matcher.find())
        {
            // do the thing
        }

我的意思是,只有你必须检查很多这些。谢谢!

3 个答案:

答案 0 :(得分:4)

我个人会使用一个集合,因为我认为它更容易阅读,contains在O(1)中效率很高:

Set<String> keywords = new HashSet<String>();
keywords.add("text");
keywords.add("foo");
keywords.add("bar");

if(keywords.contains(text)) {
    //do your thing
}

如果你喜欢紧凑,你也可以写:

Set<String> keywords = new HashSet<String>(Arrays.asList("text", "foo", "bar"));

if(keywords.contains(text)) {
    //do your thing
}

最后,如果您始终使用相同的列表,则可以创建关键字private static final,而不是每次运行该方法时重新创建它。

修改
评论之后,上述内容与使用text.equals("xxx")而非text.contains("xxx")的条件相同。如果你真的想要使用contains,那么你必须遍历集合并测试每个字符串,但它变成了O(n)操作:

for (String key : keywords) {
    if (text.contains(key)) {
        //do your stuff
        break;
    }
}

答案 1 :(得分:0)

String[] storage = {
    "text",
    "foo",
    "bar",
    "more text"
};

for(int i=0; i < storage.length(); i++){
    //Do Something
}

这有帮助吗?

答案 2 :(得分:0)

通常,长If else个语句会被case语句替换,但这并非总是可行。如果我在哪里推荐,我会选择第二个选项,选项1会给你一堆If else if else语句做同样的事情,而对于第三种情况,正则表达式往往会变得非常大很快。 / p>

再次取决于alot的数量,最终只需将所有字符串抛出到数据结构中并迭代它以查看元素是否在其中。