为什么我的包含和替换方法不正常? Java的

时间:2014-04-10 15:38:30

标签: java string replace contains

我试图制作一些东西然后我无法使用contains和replace方法编写if方法。我错过了什么?

   import java.util.Scanner;
public class replacesomething
{
    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.replace("replace", "Hi");
            System.out.println("Replaced Sentence: " + str1);
        }
        else
        {
            System.out.println("Sentence doesn't contains that...");
        }

    }

}

2 个答案:

答案 0 :(得分:2)

字符串在Java中是不可变的;一旦创建,您就无法编辑它们。相反,“替换”方法返回一个新字符串。如果为str1指定了替换结果,则会得到预期的结果。

答案 1 :(得分:1)

将替换方法调用更改为:

str1 = str1.replace("replace", "Hi");

由于String是不可变的,因此您需要将结果重新分配回str1。它不执行就地替换,而是构造并返回一个新的String对象。原始字符串未经修改。