replace StringBuilder by pattern - Java java.lang

Java examples for java.lang:StringBuilder

Description

replace StringBuilder by pattern

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        StringBuilder builder = new StringBuilder();
        String pattern = "java2s.com";
        String replacement = "java2s.com";
        replace(builder, pattern, replacement);
    }//from w ww .j av  a2s.  c o  m

    public static void replace(StringBuilder builder, String pattern,
            String replacement) {
        int len = pattern.length();
        if (replacement.length() > len) {
            builder.ensureCapacity(builder.length() + 5
                    * replacement.length());
        }
        int pos = 0;
        while ((pos = builder.indexOf(pattern, pos)) >= 0) {
            builder.replace(pos, pos + len, replacement);
            pos = pos + len;
        }
    }
}

Related Tutorials