Reputation: 41
So i'm having trouble finding the index of the first vowel in a string. This is the code I came up with but its not returning anything. Its supposed to return the index of the first vowel for example if the string was "Hello World" it should return 1 because the index of the first vowel is 'e'. If there is no vowel in the given string it should return -1.
public class Vowel
{
public static int isVowel(String s)
{
int a = -1;
for(int i = 0; i < s.length(); i++)
{
if("aeiouAEIOU".indexOf(i) >= 0)
{
a = i;
}
}
return a;
}
}
Upvotes: 0
Views: 4835
Reputation: 262
Swift 5.8 I wrote a simple function to find the index of the first vowel in a string:
func findIndexOfFirstVowel(_ word: String) -> Int {
word.map { $0.lowercased() }.firstIndex(where: { $0 == "a" || $0 == "e" || $0 == "i" || $0 == "o" || $0 == "u" })!
}
I don't recommend force unwrapping in production code, and there may be a more efficient way to check for vowels. Nonetheless, I wanted to offer this as an alternate solution.
Upvotes: 0
Reputation: 359
The reason why your method isn't returning anything is because it's checking for the index of an integer within a string of all vowels. What you should do is check the character at i within s, see if it's a vowel, and then return that index.
Also, I would recommend renaming your method to something like "indexFirstVowel". Below is a possible solution if you want to try it:
public class Vowel
{
public static void main(String[] args)
{
int x = indexFirstVowel("Hello World");
}
public static int indexFirstVowel(String s)
{
for(int i = 0; i < s.length(); i++)
{
switch(s.charAt(i))
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
return i;
default:
break;
}
}
return -1;
}
}
Upvotes: 0
Reputation: 1106
Utilize a private static method to check if a certain character is a vowel:
public static int firstVowelPos(String s) {
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (isVowel(c))
return s.indexOf(c);
}
return -1;
}
private static boolean isVowel(char c) {
return "AEIOUaeiou".indexOf(c) != -1;
}
If you don't need to check for vowels anywhere else in your code, this can be simplified by moving the vowel checking into your conditional statement:
public static int firstVowelPos(String s) {
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if ("AEIOUaeiou".indexOf(c) != -1)
return s.indexOf(c);
}
return -1;
}
Upvotes: 2