Search code examples
javastringspecial-charactersnewlinecarriage-return

How do I make multi replace() java


I have a string with \r\n, \r, \n or \" characters in it. How can I replace them faster?

What I already have is:

String s = "Kerner\\r\\n kyky\\r hihi\\n \\\"";
System.out.println(s.replace("\\r\\n", "\n").replace("\\r", "").replace("\\n", "").replace("\\", ""));

But my code does not look beautiful enough. I found on the Internet something like:

replace("\\r\\n|\\r|\\n|\\", "")

I tried that, but it didn't work.


Solution

  • You can wrap it in a method, put /r/n, /n and /r in a list. iterate the list and replace all such characters and return the modified string.

    public String replaceMultipleSubstrings(String original, List<String> mylist){
        String tmp = original;
        for(String str: mylist){
            tmp = tmp.replace(str, "");
        }
        return tmp;
    }
    

    Test:

    mylist.add("\\r");
    mylist.add("\\r\\n");
    mylist.add("\\n");
    mylist.add("\\");  // add back slash
    
    System.out.println("original:" + s);
    String x = new Main().replaceMultipleSubstrings(s, mylist);
    System.out.println("modified:" + x);
    

    Output:

    original:Kerner\r\n kyky\r hihi\n \"
    modified:Kerner kyky hihi "