/* Punters Lounge JAVA programming course * * Lesson6.java * * Author : Erik Datapunter * Date : 28/apr/2004 * * Text manipulation example program * */ public class Lesson6 { public static void main(String[ ] args) { // 2 string buffers, one to hold the existing text, one for the new text StringBuffer mytext = new StringBuffer(100); StringBuffer newtext = new StringBuffer(100); String badword = "bookmaker"; String goodword = "bookie"; int position = 0; // use the append method to put the text into the buffer mytext = mytext.append("My bookmaker is my best friend."); // use the indexOf method to find out if the search word is in the text position = mytext.indexOf(badword); // if position is -1 then the word is not in the text,.. if (position == -1) { System.out.println("The word to replace was not found."); } // ...else its in the text starting at that position else { // start the new text with the beginning of the existing text up to the found word newtext = newtext.append(mytext.substring(0,position)); // append the good word to the beginning of the new text newtext = newtext.append(goodword); // append the rest of the existing text, without the bad word, to the new text newtext = newtext.append(mytext.substring(position+badword.length())); // display the old and new text System.out.println("Old text : " + mytext.toString()); System.out.println("New text : " + newtext.toString()); } } }