Search code examples
javareplacewhitespacestringbuffer

Use StringBuffer to replace substring throughout a long string


I need to compose a long string (4324 characters) and want to use StringBuffer for this purpose. Most of the string will be whitespace but some portions contain orderdetails. They must appear at certain positions. This string will be fed into an accounting-system.

I am initializing the string with whitespace (" ") and setting the length, in this example to 64.

public class BytteTekst {
    public static void main(String[] args) {
        String t1 = "Hej, jeg æder blåbærsyltetøj!";
        String t2 = "foo";

        StringBuffer s = new StringBuffer(" ");
        s.setLength(64);

        System.out.println(t1.length());

        s.replace(0, t1.length(), t1);
        System.out.println(s);

        s.replace(t1.length() + 10, t1.length() + t2.length() + 10, t2);
        System.out.println(s);

        System.out.println(s.length());
    }
}

The output from java BytteTekst is

29
Hej, jeg æder blåbærsyltetøj!
Hej, jeg æder blåbærsyltetøj!foo
64

When I replace() string foo it appears just after the first replace(). I need to have some whitespace to get a result similar like this:

29
Hej, jeg æder blåbærsyltetøj!
Hej, jeg æder blåbærsyltetøj!          foo
64

Am I using StringBuffer the wrong way? Is it silently ignoring the whitespace I want to add?


Solution

  • The issue is that

    s.setLength(64);
    

    changes the length to 64, filling the new space with \0 characters: its contents will be:

    [' ', '\0', '\0', ... '\0'] (1 space, 63 \0s)
    

    After your second replace, the contents will be:

    ['H', 'e', 'j', ... 't', 'ø', 'j', '!', '\0' (x10), 'f', 'o', 'o', '\0', ...]
    

    So there is whitespace there, it's just non-printed whitespace.

    If you want to fill your string with spaces, rather than '\0', you can either loop through the string with a plain for loop

    for (int i = 0; i < 64; ++i) s.setCharAt(i, ' ');
    

    or hard-code a string of spaces with the correct length:

    StringBuffer s = new StringBuffer("           "); // Not 64 chars - count carefully!
    

    or you can "simply" initialize with a char[] filled with spaces:

    char[] fill = new char[64];
    Arrays.fill(fill, ' ');
    StringBuffer s = new StringBuffer(new String(fill));