【发布时间】:2020-11-23 03:46:47
【问题描述】:
好吧,基本上,我有一些代码使用 contains() 方法来检测两个字符串中是否存在特定字符。对于额外的上下文,this question 是一个很好的资源,可以帮助我了解我遇到了什么样的问题(第三个解决方案也是我为此研究过的)。无论如何,这是我的一些代码:
// code up here basically just concatenates different
// characters to Strings: stringX and stringY
if (stringX.contains("!\"#")) {
} else if (stringX.contains("$%&")) {
} else if (stringX.contains("\'()")) {
} else if (stringX.contains("!$\'")) {
} else if (stringX.contains("\"%(")) {
// literally 70+ more else-if statements
}
if (stringY.contains("!\"#")) {
} else if (stringY.contains("$%&")) {
} else if (stringY.contains("\'()")) {
} else if (stringY.contains("!$\'")) {
} else if (stringY.contains("\"%(")) {
// literally 70+ more else-if statements, all of which are
// exactly the same as those working with stringX
}
我对 Java 编程还是很陌生,所以我不确定我应该如何去做。也许这不是问题?另外,如果我可以在不使用 RegEx 的情况下解决这个问题,那就更好了;在这一点上,我对它不是很了解。但如果唯一合理的解决方案是利用它,我显然会这样做。
编辑:所有这些 else-if 语句中的代码彼此之间不会有太大的不同;基本上只是一个System.out.println(),其中包含一些关于 stringX/stringY 包含的字符的信息。
【问题讨论】:
-
每种情况的代码有何不同?
-
哦,废话,我会更新我的帖子以更好地解释这一点。
-
我们需要查看各种 if-else 块中的代码。
-
更一般地说,这里的首选答案是用多态替换条件。具体来说,您似乎有一个
Map<String, Consumer<String>>和map.entrySet().stream().filter(e -> stringX.contains(e.getKey())).findFirst().ifPresent(e -> e.getValue().accept(stringX));之类的东西。 -
是否需要此优先级?即,它只会在没有找到
!"#时搜索$%&。
标签: java performance if-statement optimization