Implement String replace algorithm with while loop - Android java.lang

Android examples for java.lang:String Algorithm

Description

Implement String replace algorithm with while loop

Demo Code

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Locale;

public class Main{


    public static String replace(String source, String subject,
            String object) {/*  w  w  w. jav  a  2  s.  c  om*/
        StringBuffer rtnStr = new StringBuffer();
        String preStr = "";
        String nextStr = source;
        String srcStr = source;

        while (srcStr.indexOf(subject) >= 0) {
            preStr = srcStr.substring(0, srcStr.indexOf(subject));
            nextStr = srcStr.substring(
                    srcStr.indexOf(subject) + subject.length(),
                    srcStr.length());
            srcStr = nextStr;
            rtnStr.append(preStr).append(object);
        }
        rtnStr.append(nextStr);
        return rtnStr.toString();
    }

}

Related Tutorials