Question

I am still working on a Project with Java and wanted to ask if someone could help me ?

I am asking me if it's possible to check a string with more than one Letter with "startsWith"?

like:

 if (string Alpha.startsWith("a"||"A"||"b"||"B"||"c"||"C"||"d"||"D")){
                        System.out.println("Wrong!");
                        System.out.println("\n");
                    }
                    else{
                        System.out.println("Wrong Key!");

Any solutions ?

Was it helpful?

Solution

char first = Character.toLowerCase(str.charAt(0));
if (first >= 'a' && first <= 'd')
{
    // etc.
}

If you want to avoid possible locale issues, you can give two ranges, one for lower case and one for upper case:

char first = str.charAt(0);
if ((first >= 'a' && first <= 'd')
    || (first >= 'A' && first <= 'D'))
{
    // etc.
}

OTHER TIPS

I would put this in new method:

private boolean myStartsWith(String... args) {
   for(String str : args) {
       if(args.startsWith(str) {
          return true;
       }
   }
   return false;
}

And then use it:

str.myStartsWith(new String[]{"a","b","c"});

As others have mentioned, this is clearly the case where regular expressions should be used:

java.util.regex.Pattern p = java.util.regex.Pattern.compile("^[a-cA-C]");
java.util.regex.Matcher m = p.matcher(alpha);  //
if (m.matches()) {
...

The best way to do this

str.matches("^[A-Da-d].+");

Try this code:

String str = "ABCDEF";
if(str.matches("(a|A|b|B|c|C|d|D).*")) {
   ...
};

Do something like this:

if (Alpha.startsWith("a") || Alpha.startsWith("A") || // and so on
private static boolean startsWith(String value, String[] chars){
    for(String check:chars){
        if(value.indexOf(check) == 0 || value.indexOf(check.toUpperCase()) == 0){
            return true;
        }
    }
    return false;
} 

Usage

   public static void main(String[] args) {
        String val1 = "A string";
        String val2 = "a string";
        String val3 = "x string";
        String[] chars = {"a","b","c","d"};

        System.out.println(startsWith(val1,chars));
        System.out.println(startsWith(val2,chars));
        System.out.println(startsWith(val3,chars));
    }

You may do like this:

    String str = "Alpha";
    String[] tar = "aAbBcCdD".split("");
    for(String s: tar) {
        if(str.startsWith(s)){
        ...your own logic
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top