posted 9 years ago

Hi,

I have a string which is a combination of a alpha prefix and a number suffix. I extract the prefix and get the number suffix of the string. Then, I do a Integer.parseInt on the suffix to get the value as an integer so that I can increment it. This works ok in general, but not when the suffix has leading zeros. In this case, I need to retain the leading zeros. So, for example, if the suffix is 001, when I parseInt it the integer value become 1 and then when I increment it, it becomes 2. I need it to be 001, 002.

Is there a way to do this?

Thanks in advance.

I have a string which is a combination of a alpha prefix and a number suffix. I extract the prefix and get the number suffix of the string. Then, I do a Integer.parseInt on the suffix to get the value as an integer so that I can increment it. This works ok in general, but not when the suffix has leading zeros. In this case, I need to retain the leading zeros. So, for example, if the suffix is 001, when I parseInt it the integer value become 1 and then when I increment it, it becomes 2. I need it to be 001, 002.

Is there a way to do this?

Thanks in advance.

Rita C.

Rita Chakras

Greenhorn

Posts: 10

Rita Chakras

Greenhorn

Posts: 10

posted 9 years ago

Yes, I do know what N is (length of String), but I don't know if the N contains leading zeros or not, and if it does how many leading zeros. So if I increment, I don't know how many zeros I should add or when I should stop adding zeros.

I suppose I could parse through the string to figure out how many zeros it has and stop when it exceeds the length of N?

I suppose I could parse through the string to figure out how many zeros it has and stop when it exceeds the length of N?

Rita C.

posted 9 years ago

if you know the length of the original string, the length of the prefix, and the length of the incremented-then-converted-to-a-string integer part, you know how many zeros to add:

input string: prefix0000123

total length:13

prefix length: 6

length of string_after_increment (124): 3

13 - 6 - 3 = 4

input string: prefix0000123

total length:13

prefix length: 6

length of string_after_increment (124): 3

13 - 6 - 3 = 4

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors

posted 9 years ago

If you use java.lang.DecimalFormat or String.format, you can specify the total number of digits. Whatever digits are not filled by the number itself are filled with zeros instead.

SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6

How To Ask Questions How To Answer Questions