String (not character) replacement

From Stack Overflow
Jump to: navigation, search
    /**
     * Simple replacement function that replaces Strings with other Strings
     * (as opposed to String.replace(char, char)).  Works much like the
     * regular expression: "s/needle/haystack/g" on a string.
     * @param haystack string to locate and insert replacements
     * @param needle string to look for
     * @param replacement string to replace with
     * @return "haystack" with all occurrences of "needle" converted to "replacement"
     */
    public static String replace(String haystack, String needle, String replacement)
    {
        if ((haystack == null) || (needle == null)) return haystack;
        int len = needle.length();
        
        if (len==0) return haystack;
        
        if (replacement == null) replacement = "";
        
        StringBuffer sb = new StringBuffer(haystack);

        //traverse backwards to stablize string indexOf position
        int start = haystack.lastIndexOf(needle);
        while (start != -1){
            sb.replace(start, start+len, replacement);
            start = haystack.lastIndexOf(needle, start -1);
        }
        
        return sb.toString();
    }

Personal tools