Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Multiple replace of literals by digits

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);
    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading