Home > Software design >  Multiple replace of literals by digits
Multiple replace of literals by digits

Time:11-08

I need to replace multiple literals by digits in a string like "FF432423FA112". "A"=0, "B"=1 etc. I've tried to do it in a loop like but it didn't work. Tried also with char array

String test = "FF432423FA112";
String[] letters = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
    for (int i=0; i<letters.length; i  ) {
        newStr = test.replace(letters[i],i);
    }

CodePudding user response:

That is because you forget to use newStr.replace, every time loop will generate the last test.replace copy character

        String test = "FF432423FA112";
        String[] letters = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
        String newStr = test;
        for (int i=0; i<letters.length; i  ) {
            newStr = newStr.replace(letters[i], i   "");
        }

        System.out.println(newStr);

CodePudding user response:

If given string is "FF432423FA112" and the expected output is "5543242350112" considering to replace only alphabets and retain number as is, below code is an example.

public class Main {
    public static void main(String[] args) {
        String test = "FF432423FA112";
        String letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        StringBuilder output = new StringBuilder();
        int value = 0;
        for (int i=0; i<test.length(); i  ) {
            char c = test.charAt(i);
            if(Character.isDigit(c)) {
                value = Character.getNumericValue(c);
            } else {
                value = letters.indexOf(c);
            }
            output.append(value);
        }
        System.out.println(output);
    }
}
  •  Tags:  
  • java
  • Related