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

前端 未结 9 2141
眼角桃花
眼角桃花 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:28

    If you want to do it in a single statement you can use:

    String strOutput = inString.replace("call me","cm").replace("as soon as possible","asap");
    

    Alternatively, if you have many such replacements, it might be wiser to store them in some kind of data structure such as a 2d-array. For example:

    //array to hold replacements
    String[][] replacements = {{"call me", "cm"}, 
                               {"as soon as possible", "asap"}};
    
    //loop over the array and replace
    String strOutput = inString;
    for(String[] replacement: replacements) {
        strOutput = strOutput.replace(replacement[0], replacement[1]);
    }
    
    System.out.println(strOutput);
    

提交回复
热议问题