/* Punters Lounge JAVA programming course * * Lesson63.java * * Author : Erik Datapunter * Date : 28/apr/2004 * * Text manipulation example program * */ public class Lesson63 { public static void main(String[ ] arguments) { // string buffers to hold the existing text StringBuffer mytext = new StringBuffer(100); // one string array to hold the word to look for String[] searchletters = new String[5]; searchletters[0] = "a"; searchletters[1] = "e"; searchletters[2] = "i"; searchletters[3] = "o"; searchletters[4] = "u"; // one int array to hold the number of times each letter is found int[] nrletters = new int[5]; // an integer to use in a for loop to loop for each letter int lettercounter = 0; // search position variables int startsearch = 0; int foundposition = 0; // use the append method to put the text into the buffer mytext = mytext.append(arguments[0]); // for the amount of letters to count do a while loop for each letter for ( lettercounter = 0 ; lettercounter < 5 ; lettercounter = lettercounter + 1) { // reset search counters startsearch = 0; foundposition = 0; /* using a while loop * * we search for the letter using the indexOf method, * with each search we move the starting position based on the * position of the previously found letter * * if no (more) letter found then foundposition becomes -1 * * so as long as foundposition is not -1 we have found a letter * */ while ((foundposition = mytext.indexOf(searchletters[lettercounter],startsearch)) != -1) { // another letter found nrletters[lettercounter] = nrletters[lettercounter] + 1; // move the start position of the search to the letter after the found letter startsearch = foundposition + 1; } } for ( lettercounter = 0 ; lettercounter < 5 ; lettercounter = lettercounter + 1) { System.out.println("Found "+searchletters[lettercounter]+" : "+nrletters[lettercounter]+" times."); } } }