Search code examples
javastring.format

String.format produces weird output


I need to format a long value to string.

The input record like:

"12353555100001112083997OOO0000003   0015900122550300099010000245000311503576L16N000012800001286  01      000179            00000510000492M00058499999    0016000001000541900818901    0045207 00<strong>0003</strong>0000016"

I'm doing some manipulation on the bolded 4 char (by converting it to long) and few other manipulations of other characters and produce a result.

The manipulation of 0003 should yield 384 and hence before inserting into the actual record I need to append '0' and should be like 0384. I used

long myValue = 384;
output = record.replace(record.substring(startIndex, endIndex), String.format("%1$4d", myValue));

But, it produces a weird output like:

1 3845551 3841112083997OOO 384003   00159001225503   9901 384245000311503576L16N 384128 3841286  01      000179             384051 384492M00058499999    0016 38401000541900818901    0045207  38403 384016

where i can see, that 384 is inserted multiple times into the record. what could be the error?


Solution

  • where i can see, that 384 is inserted multiple times into the record. what could be the error?

    replace will replace all occurrances of the first argument with the second argument.

    record.replace(record.substring(startIndex, endIndex), String.format("%1$4d", myValue));
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                           first argument                         second argument
    

    That is, if the string record.substring(startIndex, endIndex) happens to represent a string that occurs in several places in record then the second argument will end up in multiple places.

    You may want to look at StringBuilder.replace, and do something like

    record.replace(startIndex, endIndex, String.format("%1$4d", myValue));