Search code examples
javastringcontainsletter

Java checking if string contains certain letters with a certain range with contains or equals method


import.java.util.Scanner;

public class Test{
   public static void main(String[] args){
   Scanner sc = new Scanner(System.in)
   String operation = sc.nextLine();
   }
}

When I want to see, if the string operation contains certain letters, I could write f.ex.

    if(operation.contains("a") || operation.contains("b")){
        System.out.println("This is not a valid choice. Please retry!");
    }

But I want to know what to write, if the string contains letters, e.g. from a to k. If I write it with || every single time, it's not efficient. EDIT: I'm only allowed to use the methods contains and equals.


Solution

  • Try using a regex:

    if (operation.matches(".*[a-k].*") {
        ...
    }
    

    An alternative:

    boolean contains = false;
    for (char charToCheck = 'a'; charToCheck <= 'k'; charToCheck++) {
        if (operation.indexOf(charToCheck) >= 0) {
            // found something
            contains = true;
            break;
        }
    }
    

    A later update

    Oh, indexOf() is not allowed too. A version which uses nested loops:

    boolean found = false;
    for (char ch : operation.toCharArray()) {
        for (ch charToCheck = 'a'; charToCheck <= 'k'; charToCheck++) {
            if (ch == charToCheck) {
                found = true;
                break;
            }
        }
        if (found) {
            break;
        }
    }