Search code examples
javastringbuffer

Java StringBuffer dynamically append Strings at certain offset


I have a String value which has a maximum length of 629 characters. i am using StringBuffer to insert values on specific offset index.

     StringBuffer sb = new StringBuffer("                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           ");
 sb.insert(0, "IN1");

 sb.insert(23, "abcsdfsfdsffdsffd");
 sb.insert(70, "6001");
 sb.insert(75, "74");
 sb.insert(80, "arn:organization");
 sb.insert(128, "YYYYMMDDHHMMSS");
 sb.insert(142, "0");
 sb.insert(145, "arn:organization");
 sb.insert(169, "502");
 sb.insert(193, "1");
 sb.insert(223, "1");
 sb.insert(228, "6001");
 sb.insert(236, "14228");
 sb.insert(254, "1");
 sb.insert(259, "4.334");
 sb.insert(514, "Usage");
 sb.insert(594, "0");

if you can see from the sample codes, i will have to initialize the StringBuffer with literally 629 blank space... else the insert will not work.

i tried StringBuffer sb = new StringBuffer(629);

but when i tried to insert into index 23, it throws an error of index out of bounds.

is there a more elegant way to initialize the StringBuffer to insert string on index?


Solution

  • You are initializing the StringBuffer incorrectly. The StringBuffer(int) constructor does not create a string with the given length, it merely allocates capacity to handle it. The StringBuffer will still have a length of 0 at the beginning. This is causing your error.

    You need to initialize it with either the StringBuffer(CharSequence) or StringBuffer(String) constructor.

    Create a string with length 629 using any of the methods outlined in this answer and use that to initialize your StringBuffer.