Alkis Kalogeris
Alkis Kalogeris

Reputation: 17773

Check string for a given alphabet

I need to check if a string (word, no whitespaces) has any letters of a given alphabet.

String A: apple
String B: bed
Alphabet: a b c d e f

I want to compare efficiently the string with the alphabet. What I want is to check if String consists of the letters in Alphabet. For now I have my alphabet in an ArrayList and in a for loop I check if String contains the letter of the arraylist and if true then exit, else continue with the next letter. The example above for String A will return false because p and l are not part of the alphabet. But it will return true for B.

Can this be done more efficiently? Thank you for your help.

Upvotes: 1

Views: 311

Answers (2)

Bohemian
Bohemian

Reputation: 425348

Turn the "alphabet" into a regex then use String.matches(). Not sure what you're after exactly, but I'm pretty sure it's one of there two options:

To check that the word has at least one of the letters in the alphabet:

if (str.matches(".*[abcdef].*"))

To check if the word consists only of the letters of the alphabet:

if (str.matches("[abcdef]+"))

Upvotes: 1

Basmeh Awad
Basmeh Awad

Reputation: 3

check this this will give you an idea how to do this check this..http://www.tutorialspoint.com/java/lang/string_contains.htm

Upvotes: 0

Related Questions