Reputation: 142
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 ?
Upvotes: 2
Views: 2407
Reputation: 1447
Try this code:
String str = "ABCDEF";
if(str.matches("(a|A|b|B|c|C|d|D).*")) {
...
};
Upvotes: 2
Reputation: 17250
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.
}
Upvotes: 5
Reputation: 104
You may do like this:
String str = "Alpha";
String[] tar = "aAbBcCdD".split("");
for(String s: tar) {
if(str.startsWith(s)){
...your own logic
}
}
Upvotes: 0
Reputation: 94459
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));
}
Upvotes: 0
Reputation: 18945
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()) {
...
Upvotes: 2
Reputation: 95958
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"});
Upvotes: 3
Reputation: 236004
Do something like this:
if (Alpha.startsWith("a") || Alpha.startsWith("A") || // and so on
Upvotes: 1