import java.io.*; import java.util.*; /** * Provides one or two static methods to alter text * in a string. * * @author http://bumble.sf.net */ public class InsertText extends Object { //-------------------------------------------- private static String NEWLINE = System.getProperty("line.separator"); //-------------------------------------------- private String text; //-------------------------------------------- public InsertText() { this.text = ""; } //-------------------------------------------- public InsertText(String sText) { this.text = sText; } //-------------------------------------------- /** inserts a string in a string before a character */ public static String insertBefore(String sText, char cMarker, String sInsert) { char cCurrent; StringBuffer sbReturn = new StringBuffer(""); if (sText.indexOf(cMarker) == -1) { return sText; } for (int ii = 0; ii < sText.length(); ii++) { cCurrent = sText.charAt(ii); if (cCurrent == cMarker) { sbReturn.append(sInsert); sbReturn.append(cMarker); } else { sbReturn.append(cCurrent); } } //-- for return sbReturn.toString(); } //-- method: insertBefore //-------------------------------------------- /** inserts a string in a string after a character */ public static String insertAfter(String sText, char cMarker, String sInsert) { char cCurrent; StringBuffer sbReturn = new StringBuffer(""); if (sText.indexOf(cMarker) == -1) { return sText; } for (int ii = 0; ii < sText.length(); ii++) { cCurrent = sText.charAt(ii); if (cCurrent == cMarker) { sbReturn.append(cMarker); sbReturn.append(sInsert); } else { sbReturn.append(cCurrent); } } //-- for return sbReturn.toString(); } //-- method: insertAfter //-------------------------------------------- /** a main method for testing */ public static void main(String[] args) throws Exception { StringBuffer sbUsageMessage = new StringBuffer(""); sbUsageMessage.append("test usage: java InsertText char string"); sbUsageMessage.append(NEWLINE); StringBuffer sbMessage = new StringBuffer(""); if (args.length < 2) { System.out.println(sbUsageMessage); System.exit(-1); } String sText = "This is the old text"; char cCharacter = args[0].charAt(0); String sNew = args[1]; System.out.println("Using string:"); System.out.println(sText); System.out.println(""); System.out.print(".insertBefore() >"); System.out.println(InsertText.insertBefore(sText, cCharacter, sNew)); System.out.print(".insertAfter() >"); System.out.println(InsertText.insertAfter(sText, cCharacter, sNew)); } //-- main() } //-- InsertText class