remove String from StringBuilder - Java java.lang

Java examples for java.lang:StringBuilder

Description

remove String from StringBuilder

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        StringBuilder builder = new StringBuilder();
        String data = "java2s.com";
        removeString(builder, data);//from  w  w w.  ja v  a2 s  .c  o m
    }

    public static void removeString(StringBuilder builder, String data) {
        if (data == null) {
            return;
        }
        int index = indexOf(builder, data, 0);
        while (index > -1) {
            builder.delete(index, index + data.length());
            if (index + data.length() > builder.length()) {
                return;
            }
            index = indexOf(builder, data, 0);
        }
    }

    /**
     * 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