Reputation: 17
I need to search a string for vowels at the end of a four letter word. I could do an if-else tree and search each letter individually, but I would like to simplify.
You generally search for a letter by this way:
String s = four
if (s.indexOf ('i') = 4)
System.out.println("Found");
else
System.out.println("Not found");
Could I instead replace the parameter of the indexOf
with this:
s.indexOf ('a','e','i','o','u')
It would make everything a lot easier.
Unfortunately, I cannot use Regexp classes, and I'm required to only use things we have previously learned.
Upvotes: 2
Views: 6909
Reputation:
This is a job for String#matches(String)
and a suiting regular expression:
if (s.matches(".*[aeiou]$")) {
/* s ends with a vowel */
}
If using regular expressions is not allowed you could define a function for this:
static boolean endsWithVowel(String str) {
if (str == null || str.length() == 0) { /* nothing or empty string has no vowels */
return false;
}
return "aeiou".contains(str) /* str is only vowels */
|| endsWithVowel(str.substring(1)); /* or rest of str is only vowels */
}
Upvotes: 0
Reputation: 3767
Regex? I believe this works. "Any 3 word characters followed by a e i or u."
Pattern p = Pattern.compile("\\w{3}[aeiou]?");
String test = "mike";
System.out.println("matches? " + p.matcher(test).matches());
Well, if you can't use regex, then use why not something like EDIT: Modified to be inline with GaborSch's answer -- my alternate algorithm was very close, but the use of the char instead of creating another string is WAY better! Give an upvote to GaborSch!)
if(someString.length() == 4){
char c = someString.charAt(3);
if("aeiou".indexOf(c) != -1){
System.out.println("Gotcha ya!!");
}
}
Upvotes: 3
Reputation: 15758
Try this way:
char c = s.charAt(3);
if("aeiou".indexOf(c) >= 0) {
System.out.println("Found");
} else {
System.out.println("Not found");
}
The trick is that you pick the 4th character and search for it in the String of all vowels.
This is a Regexp-free one-liner solution.
Upvotes: 1
Reputation: 18712
String s = "FOUR"; // A sample string to look into
String vowels = "aeiouAEIOU"; // Vowels in both cases
if(vowels.indexOf(s.charAt(3)) >= 0){ // The last letter in a four-letter word is at index 4 - 1 = 3
System.out.println("Found!");
} else {
System.out.println("Not Found!");
}
Upvotes: 3