Replaces the part of string with another string without unnecessary deletions and insertions. - Java java.lang

Java examples for java.lang:String Replace

Description

Replaces the part of string with another string without unnecessary deletions and insertions.

Demo Code


//package com.java2s;

public class Main {

    /**/*w ww  .  j a v a2  s  .  c  om*/
     * Replaces the part of string with another string without unnecessary
     * deletions and insertions. Value is changed inplace.
     *
     * @param val       Value to be changed
     * @param start     Start index of replacement object
     * @param end       End index (one char behind end) of replacement object
     * @param seq       Sequence to be inserted instead
     */
    public static void replace(StringBuilder val, int start, int end,
            CharSequence seq) {
        int valPos = start, seqPos = 0;
        // First we char-by-char replace what we can
        for (; valPos != end && seqPos != seq.length(); ++valPos, ++seqPos)
            val.setCharAt(valPos, seq.charAt(seqPos));

        // Then we do deletion and insertion of the rest
        if (valPos < end)
            val.delete(valPos, end);
        else if (seqPos < seq.length())
            val.insert(end, seq, seqPos, seq.length());
    }
}

Related Tutorials