【问题标题】:If String contains either one of two words with IgnoreCase如果 String 包含带有 IgnoreCase 的两个单词之一
【发布时间】:2018-06-23 09:42:11
【问题描述】:

我有一个程序,用户应该能够在其中输入多少度数和刻度(摄氏度、华氏度或开尔文)。如果用户希望退出会话,程序应该退出,如果他们写“Exit, EXIT, exit, QUIT, Quit or quit”。我知道如何一次只使用其中一个来编写代码,例如:

System.out.println("Enter your value, followed by the unit (C/F/K) : ");
temp=input.nextLine();

if (temp.contains("exit")) {
    System.out.println("Ending");
    System.exit(0);
}

我希望能够编写如下内容: if (temp.containsIgnoreCase("exit" || "quit") )

谁能帮助我提供一些关于如何修复我的代码的指南?我试图在这里搜索它,但没有任何效果,只有当括号内有两个不同的单词时才会出错。

【问题讨论】:

    标签: java string contains ignore-case


    【解决方案1】:

    尝试将用户输入小写,然后与String#matches进行比较:

    if (temp.toLowerCase().matches("exit|quit")) {
        System.out.println("Ending");
        System.exit(0);
    }
    

    【讨论】:

      【解决方案2】:

      使用匹配来查找与字符串的完全匹配。你可以这样:

       String quit = "quit";
          String exit = "exit";
          if(temp.toLowerCase().matches(quit)||temp.toLowerCase().matches(exit)){
                  System.out.println("Ending");
      System.exit(0);
          }
      

      【讨论】:

        【解决方案3】:

        Tim Biegeleisen 的答案可能是要走的路。如果您像我一样只是不想使用String.toLowerCase()。您可以使用 Pattern#compile(String, int) 和不区分大小写的标志:

        Pattern pattern = Pattern.compile("exit|quit", Pattern.CASE_INSENSITIVE);
        if(pattern.matcher(temp).matches()){
            System.out.println("ending");
            System.exit(0);
        }
        

        【讨论】:

          猜你喜欢
          • 2016-12-14
          • 1970-01-01
          • 2016-05-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-06-28
          相关资源
          最近更新 更多