String Substitution

String Substitution

How can I find and replace a substring of a String?

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);  }}

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist