如何在Java中替换单个字符串中的多个单词?

如何在Java中替换单个字符串中的多个单词?

问题描述:

我正在编写一个程序,它将替换单个字符串中的多个单词。我正在使用此代码,但它正在替换单词,但给出两个不同的行结果。我想要替换多个单词并在一行中输出。

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 multiple words replaced and output in one single line.

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 strOutput = inString.replace("call me","cm");
        System.out.println(strOutput);

        String strOutput1 = inString.replace("as soon as possible","asap");
        System.out.println(strOutput1);      

    }
}


如果你想在一个语句中这样做,你可以使用:

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");

或者,如果你有很多这样的替代品,将它们存储在某种数据中可能更明智一些结构如2d阵列。例如:

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);