Java code to insert a substring

(c) 2016 by Barton Paul Levenson


Language:
Java

Dialect:
NetBeans IDE

Discussion:
Java strings are immutable--they can't be changed. To get around this asinine restriction, you need to use elaborate tricks. The main idea is to create a new string and assign that to the old string variable. All Java string variables ("String" class) are references anyway. The old version is left hanging in cyberspace, to be cleaned up later by Java's automatic garbage collector. Here's the code:


    // insert inserts substring B into string A of length L at position N.
    public String insert(String A, int N, int L, String B) {
        return A.substring(0, N) + B + A.substring(N + L);
    } // insert


Page created:05/12/2016
Last modified:  05/12/2016
Author:BPL