我正在编写一个程序来替换单个字符串中的多个单词。我正在使用这段代码,但它正在替换 word 但在两行不同的行中给出结果。我想替换多个单词并在一行中输出。
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);
}
}
最佳答案
如果你想在一条语句中完成,你可以使用:
String strOutput = inString.replace("call me","cm").replace("as soon as possible","asap");
或者,如果您有很多这样的替换,将它们存储在某种数据结构(例如二维数组)中可能更明智。例如:
//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);
关于java - 如何在 Java 中替换单个字符串中的多个单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6745154/