java string.contains in switch statement
Asked Answered
P

8

23

How can I convert the following code to switch statement?

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;
}
Punjabi answered 19/7, 2012 at 9:47 Comment(3)
There is no other way to write this, unless there is same behavior for a number of containment conditions.Biological
The switch statement.Lionize
Switch switches on finite values.Thea
S
20

There is a way, but not using contains. You need a regex.

final Matcher m = Pattern.compile("[ABCD]").matcher("aoeuaAaoe");
if (m.find())
  switch (m.group().charAt(0)) {
  case 'A': break;
  case 'B': break;
  }
Seline answered 19/7, 2012 at 9:53 Comment(8)
works only if the conditions are limited to "[ABCD]", wont work if I want to check for a random letter or wordHb
No exactly readable and intuitive, but it does the job! It could be abstracted away to commented method with a good descriptive name, then it would be just nice.Census
@Slanec Intuitiveness is totally in the eye of the beholder. To a non-programmer, no line of code in any programming language is intuitive. To someone who codes everyday with regex's, this is a direct and obvious solution.Seline
good one. just like Sangeet mentioned, if i wanna do longer words or sentences, it might need some improvements, but stillPunjabi
Kiddo, in Java 7 you are covered for longer strings, the regex syntax is only sligthly different.Seline
The problem i am seeing with this is that in the original question is creating a scenario where you are searching for multiple constant strings within 1 variable. As Sangeet mentioned in this solution it only allows you to do 1 type of searchCorydalis
@Corydalis Not sure I follow you... but you can use this technique to search for any set of strings you choose. Pattern.compile("search|for|any|of|these") and switch (m.group()) { case "search": case "for": ...)Seline
Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems. Jamie ZawinskiLilas
L
10

You can't switch on conditions like x.contains(). Java 7 supports switch on Strings but not like you want it. Use if etc.

Lem answered 19/7, 2012 at 9:50 Comment(0)
E
5

Condition matching is not allowed in java in switch statements.

What you can do here is create an enum of your string literals, and using that enum create a helper function which returns the matched enum literal. Using that value of enum returned, you can easily apply switch case.

For example:

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;
   }

}

And inside your java matching class,do something like:

Tags matchedValue=Tags.ifContains("A");
if(matchedValue!=null){
    switch(matchedValue){
       case A:
         break;
       etc...
}
Exigent answered 11/8, 2017 at 7:15 Comment(0)
W
4
@Test
public void test_try() {
    String x = "userInputA"; // -- test for condition A
    String[] keys = {"A", "B", "C", "D"};
    String[] values = {"conditionA", "conditionB", "conditionC", "conditionD"};

    String match = "default";
    for (int i = 0; i < keys.length; i++) {
        if (x.contains(keys[i])) {
            match = values[i];
            break;
        }
    }

    switch (match) {
        case "conditionA":
            System.out.println("some code for A");
            break;
        case "conditionB":
            System.out.println("some code for B");
            break;
        case "conditionC":
            System.out.println("some code for C");
            break;
        case "conditionD":
            System.out.println("some code for D");
            break;
        default:
            System.out.println("some code for default");
    }
}

Output:

some code for A
Witt answered 27/7, 2017 at 5:29 Comment(0)
H
3

No you cannot use the switch with conditions

The JAVA 7 allows String to be used with switch case

Why can't I switch on a String?

But conditions cannot be used with switch

Hb answered 19/7, 2012 at 9:53 Comment(0)
L
2

you can only compare the whole word in switch. For your scenario it is better to use if

Landpoor answered 19/7, 2012 at 9:53 Comment(0)
S
2

In Java 21

    String x = "user input";
    switch (x) {
        case String s when s.contains("A") -> {
            //condition A
        }
        case String s when s.contains("B") -> {
            //condition B
        }
        case String s when s.contains("C") -> {
            //condition D
        }
        default -> {
            //condition D;
        }
    }
Samuelson answered 17/6 at 9:52 Comment(0)
T
1

also HashMap:

String SomeString = "gtgtdddgtgtg";

Map<String, Integer> items = new HashMap<>();
items.put("aaa", 0);
items.put("bbb", 1);
items.put("ccc", 2);
items.put("ddd", 2);

for (Map.Entry<String, Integer> item : items.entrySet()) {
    if (SomeString.contains(item.getKey())) {
        switch (item.getValue()) {
            case 0:
                System.out.println("do aaa");
                break;
            case 1:
                System.out.println("do bbb");
                break;
            case 2:
                System.out.println("do ccc&ddd");
                break;
        }
        break;
    }
}
Triggerfish answered 23/7, 2020 at 16:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.