我有一个关于StringBuilder的问题。我正在尝试编写一个接受用户输入的程序:例如" DOG DOG CAT DOG DOGCAT"然后要求用户输入他们想要改变的单词以及他们想要的内容改为。然后它应该替换所有出现并打印结果。
我有一个代码:
public class ChangeSentence
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Write text: ");
String text = sc.nextLine();
StringBuilder x = new StringBuilder(text);
System.out.println("Write which word would you like to change: ");
String rep = sc.nextLine();
System.out.println("For what do you want to change it: ");
String change = sc.nextLine();
System.out.println(Pattern.compile(x.toString()).matcher(rep).replaceAll(change));
}
}
我应该如何改变它以达到结果?
谢谢!
**忘了提,我需要使用StringBuilder(没有它我知道如何写它)。
答案 0 :(得分:2)
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Write text: ");
original = sc.nextLine();
//StringBuilder x = new StringBuilder(text);
System.out.println("Write which word would you like to change: ");
String replacableWord = sc.nextLine();
System.out.println("For what do you want to change it: ");
String newWord = sc.nextLine();
String output = original.replace(replacableWord ,newWord);
System.out.println(output);
}
您只需在原始字符串和
上使用functionreplace
第一个参数是目标字符串
第二个参数是替换字符串
答案 1 :(得分:1)
最后一行应替换为:
System.out.println(text.replaceAll(rep, change));
很简单。你必须练习一点