Replace one string with another - Java java.lang

Java examples for java.lang:String Replace

Description

Replace one string with another

Demo Code

/**/*  www  .j ava 2  s  . c om*/
 * Copyright (c) 2005-2006 Aptana, Inc.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html. If redistributing this code,
 * this entire header must remain intact.
 */
//package com.java2s;

public class Main {
    /**
     * Replace one string with another
     * 
     * @param str
     * @param pattern
     * @param replace
     * @return String
     */
    public static String replace(String str, String pattern, String replace) {

        int s = 0;
        int e = 0;
        StringBuffer result = new StringBuffer();

        while ((e = str.indexOf(pattern, s)) >= 0) {
            result.append(str.substring(s, e));
            result.append(replace);
            s = e + pattern.length();
        }
        result.append(str.substring(s));
        return result.toString();

    }
}

Related Tutorials