Apr 23, 2012

Replace a String at multiple places in another string

Replace a String at multiple places in another string


String class in Java provides a number of powerful API method for string manipulation in Java. This includes replacing all occurrences of a string by another in a parent string in Java.




package com.example;


/** This class is a demo for Java Tutorial on how to replace all occurrences of a substring in Java
*
* @author Extreme Java
*
*/
public class Test {


/** This method shows how to replace string at multiple places in Java
* @param args
*/
public static void main(String[] args) {
String str1 = new String("This is is a string");

System.out.println( str1.replaceAll("is", ""));

}
}



output:
Th a string

The source code of replaceAll method in String class is:


public String replaceAll(String s, String s1) {
return Pattern.compile(s).matcher(this).replaceAll(s1);
}



As we can see in the above code that the replaceAll method uses regular expressions to replace all occurrences of a substring in another string in Java.

The replaceAll method of Matcher class in Java looks like:

public String replaceAll(String s)
{
reset();
boolean flag = find();
if(flag)
{
StringBuffer stringbuffer = new StringBuffer();
boolean flag1;
do
{
appendReplacement(stringbuffer, s);
flag1 = find();
} while(flag1);
appendTail(stringbuffer);
return stringbuffer.toString();
} else
{
return text.toString();
}
}



This also means that one can pass a regular expression as the first argument of replaceAll method

No comments:

Post a Comment