Java code to handle special characters that need to be replaced with other special characters

I am writing Java code to handle a mainframe-derived string that contains special characters that need to be replaced with other special characters, my search characters §ÄÖÜäüßö@[\]~{¦}

, and the replacement characters @[\]{}~¦§ÄÖÜßäöü

, so if the string has a {

in it I need to replace it with ä

, and my example input -"0.201322.05.2017LM-R{der Dopp"

Currently my code is

        String repChar = "§ÄÖÜäüßö@[\\\\]~{¦}@[\\\\]{}~¦§ÄÖÜßäöü";
        // Split String and Convert
        String repCharin = repChar.substring(0, repChar.length()/2-1);
        String repCharout = repChar.substring(repChar.length()/2, repChar.length()-1);          
        String strblob = new String(utf8ContentIn);
        // Convert  
        for (int j=0; j < repCharin.length();j++) {
            strblob = strblob.replace(repCharin.substring(j, 1), repCharout.substring(j, 1));                               
        }
        byte [] utf8Content = strblob.getBytes();

      

But it generates the following error:

java.lang.StringIndexOutOfBoundsException on java.lang.String.substring (String.java:1240)

\\ - escaped characters. I only need one \

+3


source to share


1 answer


Code

    String utf8ContentIn = "0.201322.05.2017LM-R{der Dopp";

    String repChar = "§ÄÖÜäüßö@[\\]~{¦}@[\\]{}~¦§ÄÖÜßäöü";
    // Split String and Convert
    String repCharin = repChar.substring(0, repChar.length() / 2);
    String repCharout = repChar.substring(repChar.length() / 2, repChar.length());
    String strblob = new String(utf8ContentIn);

    String output = strblob.chars().mapToObj(c -> {
        char ch = (char) c;
        int index = repCharin.indexOf(c);
        if (index != -1) {
            ch = repCharout.charAt(index);
        }
        return String.valueOf(ch);
    }).collect(Collectors.joining());

    System.out.println(output);

      

will print "0.201322.05.2017LM-Räder Dopp"

as you expect. Your problem here (besides wrong indices during splitting) is that you have to iterate over the input string instead of your characters. As you may face the situation when replacing Ä

with [

and after the threat [

as a special character over and over again replace it with Ä

.



Also, a single backslash must be escaped with a single backslash, so \

you need to get\\

Hope it helps!

+1


source







All Articles