Pig Latin Definitive (C++, C#, Java, VB.NET, PHP)

Igpay atinlay isway oolcay… or so they say in the world of pig latin. A childhood language that was supposed to be “secret” and only the select few would know. Little did we know back then that parents had been speaking that language ever since they were little and no way did we get anything past them. Maybe I shouldn’t have called them some nasty words. No wonder they sent me to my room with a bar of soap in my mouth. But we are programmers now and we use the language as a common exercise for string manipulation. We will dabble in the languages to cover this common exercise… right here on the Programmer’s Underground!

Yikes! Mr Rogers and Beefcake the Almighty… sounds like quite the face off. But anyways, back to the Pig Latin. The language has been around for quite awhile and is spoken by people from several English speaking countries. Even though there are many variations of the game, it is usually done by taking a word in a phrase and either adding “way” to the end of it if the word begins with a vowel (“y” included) or moving all consonants to the end of the word and then adding “ay”.

So for example… the word “eagle” would be “eagleway” and the word “happy” would be “appyhay”. Notice the “h” was moved to the end leaving “appyh” and then tacking on the “ay”.

Like I mentioned earlier, there are variations of this including endings like “yay” or “hay”. We will cover the standard version outlined above in our code. So lets get started with some C++!

// Include iostream for cout and cin
// Include string to make it easier for creating substrings
#include <iostream>
#include <string>
using namespace std;

// Declarations for our three functions
void pigLatin(char []);
string moveLetter(string);
bool isVowel(char);

int main() {
	// Collect our phrase
	char strPhrase[100];

	cout << "Enter a string to translate: ";
	cin.getline(strPhrase,100);

	// Start pulling out some words
	char *strWord;
	strWord = strtok(strPhrase, " ");

	string finaloutput;

	// Loop through each word for translation
	while (strWord != NULL) {
		pigLatin(strWord);
		strWord = strtok(NULL," ");
	}

	cout << endl;

	return 0;
}

// Controller function for determining if word starts with vowel, then add "way"
// Otherwise, pass it on for rotation and add "ay"
// Piglatin has variations in rules, this is a common form but not only form.

void pigLatin(char strWord[]) {
	if (isVowel(strWord[0])) {
		cout << strWord << "way ";
	}
	else { 
		cout << moveLetter(strWord) << "ay ";
	}
}

// Recursive function to take off a non vowel letter and put it on the end
// Recall the function until a vowel is encountered and then return the word.
string moveLetter(string strWord) {
	if (!isVowel(strWord[0])) {
		char chLetter = tolower(strWord[0]);
		return moveLetter(strWord.substr(1) + chLetter);
	}
	else { return strWord; }
}

// Simply checks if letter is a vowel. 
// For most pig latin variations, Y is considered a vowel.
bool isVowel(char chLetter) {
	char letters[] = {'a','e','i','o','u','y'};

	for (int i = 0; i < 6; i++) {
		if (tolower(chLetter) == letters[i]) { return true; }
	}

	return false;
}

We have three main parts to this process. One is the controller function “piglatin” which will check for vowels and make the appropriate call to add on “way” or to start the process of rotating the letters around and adding “ay”. The second function is moveLetter() which does the actual moving of letters to the end of each word. It calls itself over and over again (recursively) until it hits the first vowel. Then it returns the modified word back to piglatin() where it gets the ending “ay”. Lastly, we have the function isVowel() to check if the letter passed in is one of the 6 vowels… again, “y” is considered a vowel.

During this process, if any of the words are capitalized, we lowercase it before we move it to the end of the word. You can easily add in modifications for punctuation and handling other capitalization rules by simply modifying the end result after the letters have been rotated.

The main function here takes in the first 100 characters (you could expand this if you like) and breaks them into individual tokens (words) for which they each get passed for translation until all words are finished.

So how would something like this look in Java? Well, as you may know, Java came out of C++ so they are surprisingly similar.

 
import java.util.Scanner;

public class piglatin {
	public static void main(String args[]) {
		String strPhrase;
		Scanner s = new Scanner(System.in);

		// Collect our phrase
		System.out.print("Enter a string to translate: ");
		strPhrase = s.nextLine();

		// Split the phrase into words
		String pieces[] = strPhrase.split(" ");

		// Loop through each word for translation
		for (int i = 0; i < pieces.length; i++) {
			pigLatin(pieces[i]);
		}

		System.out.println();
	}


	// Controller function for determining if word starts with vowel, then add "way"
	// Otherwise, pass it on for rotation and add "ay"
	// Piglatin has variations in rules, this is a common form but not only form.

	public static void pigLatin(String strWord) {
		if (isVowel(strWord.charAt(0))) {
			System.out.print(strWord + "way ");
		}
		else { 
			System.out.print(moveLetter(strWord) + "ay ");
		}
	}


	// Recursive function to take off a non vowel letter and put it on the end
	// Recall the function until a vowel is encountered and then return the word.

	public static String moveLetter(String strWord) {
		if (!isVowel(strWord.charAt(0))) {
			char chLetter = Character.toLowerCase(strWord.charAt(0));
			return moveLetter(strWord.substring(1) + chLetter);
		}
		else { return strWord; }
	}


	// Simply checks if letter is a vowel. 
	// For most pig latin variations, Y is considered a vowel.

	public static boolean isVowel(char chLetter) {
		char letters[] = {'a','e','i','o','u','y'};

		for (int i = 0; i < 6; i++) {
			if (Character.toLowerCase(chLetter) == letters[i]) { return true; }
		}

		return false;
	}
}

The only thing that really changes drastically is the way we collect input from the user to kick off the translation process. Here we created a scanner object which collects the input line and breaks it up into the individual words. We then loop through the array of words and pass each for translation. Some other changes to note is the use of the Character class for getting the lower case of each letter and charAt() to pull individual characters from the string.

With that complete, we can lateral over into C# quite easily…

namespace piglatin_csharp {
	public partial class Form1 : Form {
		public Form1()
		{
			InitializeComponent();
		}

		// Controller function for determining if word starts with vowel, then add "way"
		// Otherwise, pass it on for rotation and add "ay"
		// Piglatin has variations in rules, this is a common form but not only form.

		void pigLatin(String strWord) {
			if (isVowel(strWord[0])) {
				txtOutput.Text += strWord + "way ";
			}
			else { 
				txtOutput.Text += moveLetter(strWord) + "ay ";
			}
		}

		// Recursive function to take off a non vowel letter and put it on the end
		// Recall the function until a vowel is encountered and then return the word.
		string moveLetter(String strWord) {
			if (!isVowel(strWord[0])) {
				char chLetter = Char.ToLower(strWord[0]);
				return moveLetter(strWord.Substring(1) + chLetter);
				
			}
			else { return strWord; }
		}

		// Simply checks if letter is a vowel. 
		// For most pig latin variations, Y is considered a vowel.
		bool isVowel(char chLetter) {
			char[] letters = {'a','e','i','o','u','y'};

			for (int i = 0; i < 6; i++) {
				if (chLetter == letters[i]) { return true; }
			}

			return false;
		}

		private void btnTranslate_Click(object sender, EventArgs e)
		{
			// Split the phrase into words
			String[] pieces = txtInput.Text.Split(' ');

			// Loop through each word for translation
			for (int i = 0; i < pieces.Length; i++) {
				pigLatin(pieces[i]);
			}
		}
	}
}

In this version of the code, we are dealing with a visual GUI component. So I have created two textboxes and a button. The textboxes are “txtInput” and “txtOutput” for entering normal text and viewing the translated text. The button called “btnTranslate” kicks off the translation process and handles the string much like Java did. We created an array of words which we then pass to pigLatin() for processing. The output is simply tacked on to whatever is in the txtOutput box.

Now that we have C# completed, lets move over to the other .NET buddy, VB.NET!

Public Class Form1

	Private Sub btnTranslate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTranslate.Click
		' Split the phrase into words
		Dim pieces() As String = txtInput.Text.Split(" ")

		Dim i As Integer
		' Loop through each word for translation
		For i = 0 To pieces.Length - 1
			pigLatin(pieces(i))
		Next
	End Sub


	' Controller function for determining if word starts with vowel, then add "way"
	' Otherwise, pass it on for rotation and add "ay"
	' Piglatin has variations in rules, this is a common form but not only form.
	Private Sub pigLatin(ByVal strWord As String)
		If isVowel(strWord(0)) Then
			txtOutput.Text += strWord + "way "
		Else
			txtOutput.Text += moveLetter(strWord) + "ay "
		End If
	End Sub


	' Recursive function to take off a non vowel letter and put it on the end
	' Recall the function until a vowel is encountered and then return the word.
	Private Function moveLetter(ByVal strWord As String) As String
		Dim chLetter As Char
		If Not isVowel(strWord(0)) Then
			chLetter = Char.ToLower(strWord(0))
			Return moveLetter(strWord.Substring(1) + chLetter)
		Else
			Return strWord
		End If
	End Function


	' Simply checks if letter is a vowel. 
	' For most pig latin variations, Y is considered a vowel.
	Private Function isVowel(ByVal chLetter As Char) As Boolean
		Dim letters() As Char = {"a", "e", "i", "o", "u", "y"}

		Dim i As Integer
		For i = 0 To 5
			If (chLetter = letters(i)) Then
				Return True
			End If
		Next

		Return False
	End Function
End Class

As everyone is probably familiar with, VB is more English like in its syntax so several of the variable definitions and the loops have to be reformatted to fit the scheme. Keep an eye on the bounds of your for loops since VB makes the range inclusive. So instead of going to i < 6 you have to use For i = 0 to 5. Notice we don't say 6. We also use the method substring() like we did in C# as well, plus we use the wrapper class "Char" to get access to the function ToLower(). And last but not least, we can't forget those script kiddies out in the trenches of PHP. I have been there friends, I have fought in the PHP mud and I won't forget you guys! So enjoy a version for you as well. This is very similar to the C++ version of the code, as PHP usually is, but of course uses the syntax of PHP and creates the arrays using the array() call. Here in the example we are calling the translate() function to kick off the process using the phrase "This is a test". Other notable changes include the use of substr() for the substrings and the minor changes to the function signatures to match PHP function calling style. So there we go, Pig Latin, spoken across the world and now across the programming world. One of these versions shown above should help you with a school assignment or provide you a start on expanding it and making that really awesome multi-million dollar project for which Google will hire you. Then you can eat up the donuts at the Googleplex and be saying to yourself "Damn, DIC is so awesome that they got me hooked up at Google, I should send them all a check for X dollars!" Even if you don't make it to Google, at least you will have learned something and hopefully take the evening off. Thank you for reading! 🙂

About The Author

Martyr2 is the founder of the Coders Lexicon and author of the new ebooks "The Programmers Idea Book" and "Diagnosing the Problem" . He has been a programmer for over 25 years. He works for a hot application development company in Vancouver Canada which service some of the biggest tech companies in the world. He has won numerous awards for his mentoring in software development and contributes regularly to several communities around the web. He is an expert in numerous languages including .NET, PHP, C/C++, Java and more.