我想知道是否可以创建一个 switch 语句
来检查输入的字符串中是否有子字符串?
我的意思是是:
- 您在控制台中输入一个字符串
- 为了方便检查,字符串修改为全部小写字母
- switch 语句检查字符串是否包含某个子字符串
最佳答案
虽然没有这样的构造,但如果您确实想要的话,可以使用 Java-8 lambda 来创建类似的东西。我并不是建议您这样做,只是一个概念验证:
public class SwitchSubstring {
private static final SwitchSubstring DONE = new SwitchSubstring(null) {
@Override
public SwitchSubstring when(String subString, Runnable r) {
return this;
}
@Override
public void orElse(Runnable r) {
}
};
private final String str;
private SwitchSubstring(String str) {
this.str = str;
}
public SwitchSubstring when(String subString, Runnable r) {
if(str.contains(subString)) {
r.run();
return DONE;
}
return this;
}
public void orElse(Runnable r) {
r.run();
}
public static SwitchSubstring of(String str) {
return new SwitchSubstring(str);
}
}
使用示例:
SwitchSubstring.of("some test string")
.when("foo", () -> System.out.println("Foo is there!"))
.when("bar", () -> System.out.println("Bar is there!"))
.when("test", () -> System.out.println("Test is there!"))
.orElse(() -> System.out.println("Nothing found"));
打印“测试就在那里!”
。
关于java - 使用 Switch 语句检查字符串中的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32105783/