package javasomethingsomething; public class Main { public static void main(String[] args) { // all the heavy lifting is done in the PigLatin class PigLatin pg = new PigLatin(); String pigSentence = ""; String sentence = "This is going to be a pig latin sentence"; // iterate over the sentence with for-each and split by " " for (String s:sentence.split(" ")) { pigSentence += pg.getPigLatinForWord(s) + " "; } // added the trim to remove the trailing space System.out.println(pigSentence.trim()); } } class PigLatin{ public String getPigLatinForWord(String word) { int firstVowel = word.length(); // yes, I included y as a vowel!! String[] vowels = {"a", "e", "i", "o", "u", "y"}; for(String s:vowels){ // if indexOf() finds no match it returns -1 if ((word.indexOf(s) < firstVowel) && (word.indexOf(s) != -1)) { firstVowel = word.indexOf(s); } } return word.substring(firstVowel, word.length()) + word.substring(0, firstVowel) + "ay"; } }
Showing posts with label split. Show all posts
Showing posts with label split. Show all posts
Tuesday, October 6, 2009
Java - pig latin generator
Friday, September 25, 2009
Java - reverse the word order of a sentence
public class Main { public static void main(String[] args) { Words w = new Words(); String sentence = "The example sentence is here"; System.out.println(sentence); System.out.println("reversed to:"); System.out.println(w.reverseWordOrderOfSentence(sentence)); } } class Words{ public String reverseWordOrderOfSentence(String sentence){ // split up by words String[] words = sentence.split(" "); sentence = ""; // iterate backward through the array // rebuilding the sentence from the back forward for (int i=words.length; i>0; i--){ sentence += words[i-1]; sentence += " "; } // remove the trailing white space return sentence.trim(); } } /* * OUTPUT: The example sentence is here reversed to: here is sentence example The */
Subscribe to:
Posts (Atom)