0

I was trying to make something then i couldn't write an if method with contains and replace method. What was i missing?

   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
    Strings are *immutable* in Java. You can't change them. All methods that "modify" a `String` ... don't. They return a new one. – Brian Roach Apr 10 '14 at 15:41

2 Answers2

3

Strings are immutable in Java; you can't edit them once created. Instead, the "replace" method returns an new string. If you assign str1 with the result of replace you will get the result you expect.

Dave
  • 95
  • 8
  • Thank you i got it but if i write "replace and something else" it prints "Hi" only. How can i do it for one word instead of all sentence? I mean, I want to print "Hi and something else". – İsmail Samir USTA Apr 10 '14 at 16:09
2

Change the replace method call to:

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

Since String are immutable, you need to reassign the result back to str1. It doesn't perform in-place replacement, rather it constructs and returns a new String object. the original String is unmodified.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • Thank you i got it but if i write "replace and something else" it prints "Hi" only. How can i do it for one word instead of all sentence? I mean, I want to print "Hi and something else". – İsmail Samir USTA Apr 10 '14 at 16:06