Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeated replacement of characters in String

I'm trying to create an Android app which converts normal hex code to inverted one which is used in smali. Everything works perfectly except for that when I use the replace or replaceAll method on String, it even replaces the already replaced characters

For example,

String stringInvert = string.replace("F", "0")
    .replace("E" , "1")
    .replace("D" , "2")
    .replace("C" , "3")
    .replace("B" , "4")
    .replace("A" , "5")
    .replace("9" , "6")
    .replace("8" , "7")
    .replace("7" , "8")
    .replace("6" , "9")
    .replace("5" , "A")
    .replace("4" , "B")
    .replace("3" , "C") 
    .replace("2" , "D")
    .replace("1" , "E")
    .replace("0" , "F"); 

As you can see that first F is changed to 0, and similarly other letters are also changed, but later 0 is changed to F, which also changes the already changed F back to F. So, all in all, only the letters/numbers that are before 7 get inverted(as they are replaced after in the code) and others remain same due to dual inversion. I even tried replaceAll method, it gives the same result. So is there any other way or a work around to this problem?

Full code is here - http://pastebin.com/dB23JmQG

Sorry if the code is ugly, I did it in AIDE

Thanks

like image 882
iamareebjamal Avatar asked Mar 20 '23 14:03

iamareebjamal


2 Answers

You could create a Map<Character, Character> which will hold your mapping.

Then just iterate other the original String.

Map<Character, Character> m = new HashMap<>();
m.put('F','0');
....

StringBuilder sb = new StringBuilder();
for(char c : originalString.toCharArray()){
   sb.append(map.get(Character.toUpperCase(c)));
} 
String finalString = sb.toString();
like image 110
Alexis C. Avatar answered Mar 23 '23 05:03

Alexis C.


You can try to replace with multiple steps like this:

String stringInvert = string
.replace("F", "null")
.replace("E" , "one")
.replace("D" , "two")
.replace("C" , "three")
.replace("B" , "four")
.replace("A" , "five")
.replace("9" , "six")
.replace("8" , "seven")
.replace("7" , "8")
.replace("6" , "9")
.replace("5" , "A")
.replace("4" , "B")
.replace("3" , "C") 
.replace("2" , "D")
.replace("1" , "E")
.replace("0" , "F")
.replace("null", "0")
.replace("one","1")
.replace("two","2" )
.replace("three","3" )
.replace("four","4" )
.replace("five","5" )
.replace("six","6" )
.replace("seven","7" );

Not nice and smart, but simple and working :)

like image 27
alex Avatar answered Mar 23 '23 05:03

alex