我需要将长值格式化为字符串。
输入记录如:
"12353555100001112083997OOO0000003 0015900122550300099010000245000311503576L16N000012800001286 01 000179 00000510000492M00058499999 0016000001000541900818901 0045207 00<strong>0003</strong>0000016"
我正在对加粗的 4 个字符(通过将其转换为长字符)进行一些操作,并对其他字符进行一些其他操作并生成结果。
0003
的操作应该产生 384
因此在插入到实际记录之前我需要附加“0”并且应该像 0384
。我用过
long myValue = 384;
output = record.replace(record.substring(startIndex, endIndex), String.format("%1$4d", myValue));
但是,它会产生一个奇怪的输出,例如:
1 3845551 3841112083997OOO 384003 00159001225503 9901 384245000311503576L16N 384128 3841286 01 000179 384051 384492M00058499999 0016 38401000541900818901 0045207 38403 384016
我可以看到,384 被多次插入到记录中。可能是什么错误?
最佳答案
where i can see, that 384 is inserted multiple times into the record. what could be the error?
replace 将用第二个参数替换所有出现的第一个参数。
record.replace(record.substring(startIndex, endIndex), String.format("%1$4d", myValue));
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
first argument second argument
也就是说,如果字符串 record.substring(startIndex, endIndex)
恰好表示一个字符串出现在 record
中的几个地方,那么第二个参数将结束在多个地方。
你可能想看看StringBuilder.replace
,然后做类似的事情
record.replace(startIndex, endIndex, String.format("%1$4d", myValue));
关于java - String.format 产生奇怪的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25868119/