startsWith(String) method and arrays

user1793532 picture user1793532 · Nov 2, 2012 · Viewed 8.2k times · Source

I have to take a string and convert the string to piglatin. There are three rules to piglatin, one of them being:

if the english word starts with a vowel return the english word + "yay" for the piglatin version.

So i tried doing this honestly expecting to get an error because the startsWith() method takes a string for parameters and not an array.

 public String pigLatinize(String p){
    if(pigLatRules(p) == 0){
        return p + "yay";
    }
}

public int pigLatRules(String r){
    String vowel[] = {"a","e","i","o","u","A","E","I","O","U"};
    if(r.startsWith(vowel)){
        return 0;
    }        
}

but if i can't use an array i'd have to do something like this

if(r.startsWith("a")||r.startsWith("A")....);
     return 0;

and test for every single vowel not including y which would take up a very large amount of space, and just personally I would think it would look rather messy.

As i write this i'm thinking of somehow testing it through iteration.

 String vowel[] = new String[10];
 for(i = 0; i<vowel[]; i++){
     if(r.startsWith(vowel[i]){
         return 0;
     }

I don't know if that attempt at iteration even makes sense though.

Answer

Vaibhav Desai picture Vaibhav Desai · Nov 2, 2012

Put all those characters in a HashSet and then just perform a lookup to see if the character is valid or not and return 0 accordingly.

Please go through some example on HashSet insert/lookup. It should be straightforward.

Hope this helps.