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

前端 未结 9 2130
眼角桃花
眼角桃花 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:30
        String strOutput1 = inString.replace("as soon as possible","asap");
    

    You should change that to

        String strOutput1 = strOutput .replace("as soon as possible","asap");
    
    0 讨论(0)
  • 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"

    0 讨论(0)
  • 2020-12-11 17:32

    Use System.out.print() instead of System.out.println()

    0 讨论(0)
提交回复
热议问题