Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java Language
Expertise: Beginner
May 9, 1999

String Substitution

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 new String 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);
  }
}
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date