Performs in-place replacement of all occurences of a given text in StringBuilder - Java java.lang

Java examples for java.lang:StringBuilder

Description

Performs in-place replacement of all occurences of a given text in StringBuilder

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        StringBuilder builder = new StringBuilder();
        String searchText = "java2s.com";
        String replacementText = "java2s.com";
        replaceAll(builder, searchText, replacementText);
    }/* ww w .  j av  a  2 s .  c  o  m*/

    /**
     * Performs in-place replacement of all occurences of a given text
     */
    public static void replaceAll(StringBuilder builder, String searchText,
            String replacementText) {
        int index = builder.indexOf(searchText);
        while (index != -1) {
            builder.replace(index, index + searchText.length(),
                    replacementText);
            index += replacementText.length(); // Move to the end of the replacement
            index = builder.indexOf(searchText, index);
        }
    }
}

Related Tutorials