Algorithm to replace All substring - Android java.lang

Android examples for java.lang:String Substring

Description

Algorithm to replace All substring

Demo Code

import java.util.Vector;

public class Main{

    public static String replaceAll(String input, String searchStr,
            String replaceWithStr) {
        StringBuffer buffer = new StringBuffer();
        int startIndex = 0;
        int oldIndex = 0;

        if (input.indexOf(searchStr) == -1) {
            return input;
        }// ww w .  j a v a 2 s .  c  o  m

        while ((startIndex = input.indexOf(searchStr, oldIndex)) != -1) {
            buffer.append(input.substring(oldIndex, startIndex));
            buffer.append(replaceWithStr);
            startIndex += searchStr.length();
            oldIndex = startIndex;

            if (oldIndex >= input.length()) {
                break;
            }
        }

        if (oldIndex < input.length()) {
            buffer.append(input.substring(oldIndex));
        }

        return buffer.toString();
    }

}

Related Tutorials