Faster alternatives to replace method in a Java String?

后端 未结 10 1407
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-14 11:07

The fact that the replace method returns a string object rather than replacing the contents of a given string is a little obtuse (but understandable when you know that strin

10条回答
  •  爱一瞬间的悲伤
    2020-12-14 11:42

    The follow code is approx. 30 times faster if there is no match and 5 times faster if there is a match.

    static String fastReplace( String str, String target, String replacement ) {
        int targetLength = target.length();
        if( targetLength == 0 ) {
            return str;
        }
        int idx2 = str.indexOf( target );
        if( idx2 < 0 ) {
            return str;
        }
        StringBuilder buffer = new StringBuilder( targetLength > replacement.length() ? str.length() : str.length() * 2 );
        int idx1 = 0;
        do {
            buffer.append( str, idx1, idx2 );
            buffer.append( replacement );
            idx1 = idx2 + targetLength;
            idx2 = str.indexOf( target, idx1 );
        } while( idx2 > 0 );
        buffer.append( str, idx1, str.length() );
        return buffer.toString();
    }
    

提交回复
热议问题