Java 如何用包含和替换方法替换单词而不是整个句子?
我已经写了这段代码,但我有一个问题。我想在写“替换其他东西。我怎么做?”Java 如何用包含和替换方法替换单词而不是整个句子?,java,string,replace,contains,Java,String,Replace,Contains,我已经写了这段代码,但我有一个问题。我想在写“替换其他东西。我怎么做?” import java.util.Scanner; public class replace something { public static void main(String[] args) { Scanner cumle = new Scanner(System.in); System.out.println("Enter the sentence u want to
import java.util.Scanner;
public class replace something
{
public static void main(String[] args)
{
Scanner cumle = new Scanner(System.in);
System.out.println("Enter the sentence u want to replace :");
String str1 = cumle.next();
if (str1.contains("replace"))
{
str1 = str1.replace("replace", "Hi");
System.out.println("Replaced Sentence: " + str1);
}
else
{
System.out.println("Sentence doesn't contains that...");
}
}
}
您正在打印的是
str1
,而不是str
:
更改此项:
System.out.println("Replaced Sentence: " + str1);
为此:
System.out.println("Replaced Sentence: " + str);
首先,您必须使用
nextLine()
读取整行,因为next()
只读取下一个标记
此外,如果要修改原始字符串,必须将replace()
的结果分配给str1
:
str1 = str1.replace("replace", "Hi");
代码:
Scanner cumle = new Scanner(System.in);
System.out.println("Enter the sentence u want to replace :");
String str1 = cumle.nextLine();
if (str1.contains("replace")) {
str1 = str1.replace("replace", "Hi");
System.out.println("Replaced Sentence: " + str1);
} else {
System.out.println("Sentence doesn't contains that...");
}
检查您正在打印的字符串…要详细说明,请修复输入错误:
System.out.println(“替换句子:+str”);