Question:
How can I find and replace a substring of a String?
Answer:
The String class is immutable. That is, once you have created a String, you cannot change its value. Therefore, to perform a substitution, you must create a newString in the process. The key to performing a substitution is finding the substring. You can do this with indexOf(String), which returns the index of the first occurrence of a substring in a String. Once you have the index, you need to identify the parts of the string surrounding the substring. The substring(int start, int end) method gives you these values. The following code example shows how to use these methods to perform a substitution.
/*** * This program demonstrates how to find and replace the first occurrence * of a substring in a string. ***/public class SubstituteString { public static String substitute(String input, String substring, String substitute) { int result; StringBuffer newstring; result = input.indexOf(substring); if(result < 0) return null; newstring = new StringBuffer(); newstring.append(input.substring(0, result)); newstring.append(substitute); newstring.append(input.substring(result + substring.length())); return newstring.toString(); } public static void main(String[] args) { int result; String newstring; if(args.length < 3) { System.err.println( "Usage: SubstituteString string substring substitution"); return; } newstring = substitute(args[0], args[1], args[2]); if(newstring == null) System.out.println("Input string does not contain substring."); else System.out.println("New string: " + newstring); }}
Charlie has over a decade of experience in website administration and technology management. As the site admin, he oversees all technical aspects of running a high-traffic online platform, ensuring optimal performance, security, and user experience.






















