I recreated the Pig Latin game on Java. The program takes an arbitrary number of command line arguments as words, and prints to the standard output these words translated with following rules:
- For words that begins with a consonants, all letters until first vowel are moved to the end, and it is added the sequence "ay";
- For words that begins with a vowel, it is simply added the sequence "way".
About the implementation, I've used a regular expression to split the word. I think that it is an elegant solution, maybe less efficient against a specific implementation of the rules.
The code is composed only with a class, PigLatin
. You can compile it with javac PigLatin.java
and run with java PigLatin <word> ...
. Here there is PigLatin.java:
/**
* This small program implements the game Pig Latin. You can specify one or more
* words as a command line argument, and the program will print the modified
* version on the standard output.
*
* The rules of the game are:
* - For words that begin with a consonant, all letters before the first
* vowel are placed at the end of the word, then the sequence "ay" is
* appended.
* - For words that begin with a vowel, it is appended the sequence "way".
*
* Note that command line arguments are limited.
*
* Note that you should only use uppercase or lowercase letters.
*/
public class PigLatin {
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
System.out.print(convertWord(args[i]));
if (i < args.length - 1)
System.out.print(" ");
else
System.out.println();
}
}
/*
* This method convert a word using Pig Latin rules.
*
* @param word the word to convert
*
* @return the converted word
*/
private static String convertWord(String word) {
/* If the word begins with a consonant (or more), this regex splits the
* word into two groups: the first are the consonants before the first
* vowel, the second is the rest of the string.
* If the word begins with a vowel, only a single group is returned.
*/
String[] tokens = word.split("^([^aeiouAEIOU]*)(\\w*)");
if (tokens.length == 2)
return String.join(tokens[1], tokens[0], "ay");
else
return word + "way";
}
}