0

How would you take a string and replace it to another word? I know how to use char arrays and replace words with other words. But, say I have a sentence, "I like cake". How would I replace the word "like" to "ate" and then put "ate" back into the original message? So, instead of "I like cake", the message would now be "I ate cake". If anyone could help me, that would be great! I am still a beginner at Java so please don't hate. Thanks guys!

3 Answers3

2

For replacing any thing java.lang.String class provides three replace method which are

  1. String replace(char oldChar, char newChar) Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.

  2. String replaceAll(String regex, String replacement) Replaces each substring of this string that matches the given regular expression with the given replacement.

  3. String replaceFirst(String regex, String replacement) Replaces the first substring of this string that matches the given regular expression with the given replacement.List item

By using these three methods you can replace any thing from given string

for example

String str =" i like cake";
 String str2 = str.replace("like", "ate");

System.out.println("replaced string is "  +  str2);

for more information you can check here.

Arvind
  • 1,548
  • 17
  • 23
1

Not sure if this is what you mean, but...

String message = "I like cake";
message = message.replace("like", "ate");

System.out.println(message);
I ate cake

Take a look at the documentation of the String class.

arshajii
  • 127,459
  • 24
  • 238
  • 287
1
System.out.println("I like cake".replace("like", "ate"));
Ravi K Thapliyal
  • 51,095
  • 9
  • 76
  • 89