Pig Latin Edit

I'm trying to get user entered sentence and translate it to Pig Latin. How should I edit my code? Constants I have to take the first letter and place in back then add "ay". Vowels you just add "-way". Thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
string PigV (string myString) {
    for (int i = 0; i < myString.size(); i++) {
        if (myString[i] == 'a' || myString[i] == 'e' || myString[i] == 'i' || myString[i] == 'o' || myString[i] == 'u' || myString[i] == 'y')
                myString += "-way";
    }
    return myString;
}

string PigC (string myString) {
    for (int i = 0; i < myString.size(); i++) {
         if (myString[i] != ' ' && myString[i] != 'a' && myString[i] != 'e' && myString[i] != 'i' && myString[i] != 'o' && myString[i] != 'u' && myString[i] != 'y')
                myString += "ay";
    }
    return myString;
}
To avoid having a really long on line 3, use a switch statement instead.

Same for line 11, except that you will use the default clause because you want consonants not vowels.

The thing that attracts my attention is the really long if conditions where there is a pattern. I personally detest the one on line 11 (that is just my view though). A switch is much better because it is scalable.

If you are not sure how a switch works - read about here:

http://www.cplusplus.com/doc/tutorial/control/


Is Y a vowel? maybe it is part of the Pig Latin conversion?

You code does not cater for upper-case, so this is another advantage of using the switch.

Hope all goes well, I look forward to seeing your new code.
You shouldn't have two separate conversion functions, at least not functions that test for whether they should or shouldn't modify the string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
bool is_vowel(char ch)
{
    ch = std::tolower(ch) ;   // #include <cctype> for tolower
    std::string vowels( "aeiou") ;
    return vowels.find(ch) != std::string::npos ;
}

std::string toPigLatin(const std::string& s)
{
    std::string result = s ;
    if ( result.length() )
    {
        if ( is_vowel(result[0]) )
             result += "way" ;
        else
        {
             // remove first letter.
             // append former first letter + "ay" to string.
        }
    }
    return result ;
}
Topic archived. No new replies allowed.