nob
nob

Reputation: 1077

replace does not replace digits

I want to replace in a string every '0' with a 'F', every '1' with a 'E' and so on.

e.g. "234567890ABCDEF" should result in "DCBA9876543210"

            final char[] items = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        for (int i = 0; i < 16; i++) {
            newString = oldString.replace(items[i], items[15-i]);
        }

unfortunately, this piece of code does not work. It replaces all Letters but not the digits. Any suggestions, why? I'm really at a loss...

Upvotes: 0

Views: 270

Answers (3)

Daniel
Daniel

Reputation: 28084

This is because you invert the result done during the first eight replacements in your second replacements! This meant,

0-7 are converted back to 0-7, but 8 and 9 will be converted to their conterparts!

Upvotes: 0

Boris
Boris

Reputation: 4537

If you add debug to your code and look at the iterations you'll notice how you overwrite the results of the first iterations with the replace()es of the last iterations:

234567890ABCDEF
23456789FABCDEF
23456789FABCDEF
D3456789FABCDEF
DC456789FABCDEF
DCB56789FABCDEF
DCBA6789FABCDEF
DCBA9789FABCDEF
DCBA9889FABCDEF
DCBA9779FABCDEF
DCBA6776FABCDEF
DCB56776F5BCDEF
DC456776F54CDEF
D3456776F543DEF
23456776F5432EF
23456776F54321F
234567760543210

Upvotes: 0

rsp
rsp

Reputation: 23373

Your problem is that you replace the digits to letters for i=0 to 7 and back for i=8 to 15.

Upvotes: 2

Related Questions