Replace occurrences into a string - Java java.lang

Java examples for java.lang:String Replace

Description

Replace occurrences into a string

Demo Code

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Vector;

public class Main{

    public static void main(String[] argv){
        String data = "java2s.com";
        String from = "book";
        String to = "asdfasdfasdfasdf";
        System.out.println(replace(data,from,to));
    }/*  w w  w.  ja  v a2 s.c om*/
    /**
     * Replace occurrences into a string.
     *
     * @param data
     *            the string to replace occurrences into
     * @param from
     *            the occurrence to replace.
     * @param to
     *            the occurrence to be used as a replacement.
     * @return the new string with replaced occurrences.
     */
    public static String replace(String data, String from, String to) {
        StringBuffer buf = new StringBuffer(data.length());
        int pos = -1;
        int i = 0;
        while ((pos = data.indexOf(from, i)) != -1) {
            buf.append(data.substring(i, pos)).append(to);
            i = pos + from.length();
        }
        buf.append(data.substring(i));
        return buf.toString();
    }

}

Related Tutorials