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

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

    Of course it prints two lines: you have two print statements. Use this code:

    import java.util.*;
    
    public class ReplaceString {
        public static void main(String[] args) {
            new ReplaceString().run();
        }
    
        public void run()
        {
    
            System.out.println("Input String:\n");////
            Scanner keyboardScanner = new Scanner(System.in);/////
            String inString = keyboardScanner.nextLine();/////
            String shortMessage = shortifyMessage(inString);
            System.out.println(shortMessage);
        }
    
        public String shortifyMessage(String str)
        {
            String s = str;
            s = s.replace("call me", "cm");
            s = s.replace("as soon as possible", "asap");
            // Add here some other replacements
    
            return s;
        }
    }
    

提交回复
热议问题