在switch语句中使用java string.contains

Kid*_*ddo 15 java switch-statement

如何将以下代码转换为switch语句?

String x = "user input";

if (x.contains("A")) {
    //condition A;
} else if (x.contains("B")) {
    //condition B;
} else if(x.contains("C")) {
    //condition C;
} else {
    //condition D;
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*nik 17

有一种方法,但没有使用contains.你需要一个正则表达式.

final Matcher m = Pattern.compile("[ABCD]").matcher("aoeuaAaoe");
if (m.find())
  switch (m.group().charAt(0)) {
  case 'A': break;
  case 'B': break;
  }
Run Code Online (Sandbox Code Playgroud)

  • @Slanec Intuitiveness完全在旁观者眼中.对于非程序员来说,任何编程语言中的代码行都不直观.对于每天用正则表达式编码的人来说,这是一个直接而明显的解决方案. (3认同)

小智 7

你不能switch在这样的条件下x.contains().Java 7支持switchStrings但不是你想要它.使用if


Anu*_*aya 5

java中的switch语句中不允许条件匹配。

您可以在这里做的是创建字符串文字的枚举,并使用该枚举创建一个辅助函数,该函数返回匹配的枚举文字。使用返回的枚举值,您可以轻松应用switch case

例如:

public enum Tags{
   A("a"),
   B("b"),
   C("c"),
   D("d");

   private String tag;

   private Tags(String tag)
   {
      this.tag=tag;
   }

   public String getTag(){
      return this.tag;
   }

   public static Tags ifContains(String line){
       for(Tags enumValue:values()){
         if(line.contains(enumValue)){
           return enumValue;
         }
       }
       return null;
   }

}
Run Code Online (Sandbox Code Playgroud)

在您的 Java 匹配类中,执行以下操作:

Tags matchedValue=Tags.ifContains("A");
if(matchedValue!=null){
    switch(matchedValue){
       case A:
         break;
       etc...
}
Run Code Online (Sandbox Code Playgroud)