java - 使用 Switch 语句检查字符串中的子字符串

标签 java string switch-statement java-8 substring

我想知道是否可以创建一个 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/

相关文章:

c++ - 有没有办法丢弃空捕获?

c - 使用 || 检查长案例语句的更快方法状况

java - 删除 PDF/A 上的 XMP 元数据

java - 在网格 jpanel 中复制元素

java - 在java中检查 HashMap 上的正则表达式模式列表的有效和最快的方法是什么

iOS : Is there a way to replace string that moSTLy like same?

java - 在oracle数据库中调用java存储过程时出错

java - 我编写了这段代码,用于从字符串中删除特定单词

iphone - 以编程方式切换自定义 View (推送和弹出)

c - switch 语句中的变量定义