How to replace multiple words in a single string in Java?

前端 未结 9 2137
眼角桃花
眼角桃花 2020-12-11 17:09

I\'m writing a program that will replace multiple words in a single string. I\'m using this code but it is replacing word but giving result in two different lines. I want

9条回答
  •  执念已碎
    2020-12-11 17:32

    All above answers could be correct. However, replacing each string once is not efficient. Following code from Apache Commons StringUtils will help it to efficiently replace all the strings in one go.

        System.out.println("Input String:\n");////
        Scanner keyboardScanner = new Scanner(System.in);/////
        String inString = keyboardScanner.nextLine();/////
    StringUtils.replaceEach(inString, new String[]{"call me", "as soon as possible"}, new String[]{"cm", "asap"});
    

    Please note that: above method doesn't work on replacing the words in previous substitution result. For example:

    StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"})
    

    will give result : "dcte"

提交回复
热议问题