如何用contains和replace方法替换单词而不是整个句子?

时间:2014-04-10 17:02:50

标签: 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 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...");
        }

    }

}

2 个答案:

答案 0 :(得分:0)

您正在打印str1而不是str

改变这个:

System.out.println("Replaced Sentence: " + str1);

到此:

System.out.println("Replaced Sentence: " + str);

答案 1 :(得分:0)

首先,您必须使用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...");
}