StringBuilder replace String - Java java.lang

Java examples for java.lang:StringBuilder

Description

StringBuilder replace String

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        StringBuilder builder = new StringBuilder();
        CharSequence replace = "java2s.com";
        CharSequence replaceWith = "java2s.com";
        replaceString(builder, replace, replaceWith);
    }//from ww  w  .  j a  v a2s  .co m

    public static void replaceString(StringBuilder builder,
            CharSequence replace, CharSequence replaceWith) {
        int index = indexOf(builder, replace, 0);
        while (index > -1) {
            builder.delete(index, index + replace.length());
            builder.insert(index, replaceWith);
            index = indexOf(builder, replace, index + 1);
        }
    }

    /**
     * the index of method for abstract string builders & strings wants a char
     * array, and that means that many of the CharSequence objects have to copy
     * their data into a new array. try to save some allocations, try to use
     * CharSequence.charAt() which is a really fast call for those same objects.
     * 
     * @param source
     *            the characters being searched.
     * @param sourceOffset
     *            offset of the source string.
     * @param sourceCount
     *            count of the source string.
     * @param target
     *            the characters being searched for.
     * @param targetOffset
     *            offset of the target string.
     * @param targetCount
     *            count of the target string.
     * @param fromIndex
     *            the index to begin searching from.
     * @return
     */
    static int indexOf(CharSequence source, CharSequence target,
            int fromIndex) {
        if (source.length() == 0) {
            return -1;
        }

        if (target.length() == 0) {
            return -1;
        }

        if (target.length() > source.length()) {
            return -1;
        }

        for (int i = fromIndex; i < source.length(); i++) {
            int firstMatch = 0;
            if (source.charAt(i) == target.charAt(0)) {
                firstMatch = i;
                int j = 0;
                for (j = 0; j < target.length(); j++) {
                    if (target.charAt(j) != source.charAt(i)) {
                        // go backwards and re-try
                        i = i - j;
                        break;
                    }
                    i++;
                }
                if (j == target.length()) {
                    return firstMatch;
                }
            }
        }
        return -1;
    }
}

Related Tutorials