Reputation: 149
I have a String miscFlag which is of size 100. I need to append to this miscFlag starting from index 20 as 0-19 are reserved for some other info. And then append subsequently at certain positions only. Can we do this using StringBuilder/StringBuffer?
This is how i am trying to do it..
StringBuilder info = new StringBuilder(miscFlag);
info.append(" ");
info.append(Misc.toTimestampLiteral(currentDate));//append this from pos 20
info.append(" ");
info.append(formattedStartTime); //append this from pos 40
Here i am not able to specify the position from where to append.
Upvotes: 1
Views: 19088
Reputation: 3
You can specify the sposition where you'd like to insert as below
StringBuilder info = new StringBuilder(miscFlag);
info.insert(19, Misc.toTimestampLiteral(currentDate) + " ");
info.insert(39, formattedStartTime + " ");
Upvotes: 0
Reputation:
Use the insert method.
info.insert(19, Misc.toTimestampLiteral(currentDate));
Upvotes: 3
Reputation: 21718
Fixed length fields are doable with StringBuilder
but looks for me very clumsy and error-prone, I would not recommend. Use String.format, it is exactly for that you need - to create string where field widths and positions are important:
String.format("A[%8s][%4s]", "ab","cd");
will result
A[ ab][ cd]
Upvotes: 0
Reputation: 41200
Use String#subString
to cut 0 to 20 index and then add new String.
String str = miscFlag.substring(0,20)+ " "+Misc.toTimestampLiteral(currentDate)+" "+ miscFlag.substring(21);
Upvotes: 1