Instructions:
Single Word Pig Latinjava
Solution:
public class PigLatin{
public String translate(String str){
if (str == null || str.equals("") || !str.matches("[a-zA-Z]+")) {
return null;
}
StringBuilder sb = new StringBuilder(str.toLowerCase());
boolean startWithVowel = false;
int index = -1;
for (int i = 0; i < sb.length(); i++) {
char c = sb.charAt(i);
if ("aeiou".indexOf((int) c) != -1) {
if (i == 0) {
startWithVowel = true;
}
index = i;
break;
}
}
for (int i = 0; i < index; i++) {
sb.append(sb.charAt(i));
}
if (index != -1 && !startWithVowel) {
sb.delete(0, index);
}
return startWithVowel ? sb.toString() + "way" : sb.toString() + "ay";
}
}
Example Tests:
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class TestPigLatin {
private PigLatin p;
@Before
public void setUp() throws Exception {
p = new PigLatin();
}
@Test
public void testMap() {
assertEquals("apmay", p.translate("map"));
}
@Test
public void testegg() {
assertEquals("eggway", p.translate("egg"));
}
@Test
public void testspaghetti() {
assertEquals("aghettispay", p.translate("spaghetti"));
}
}