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!
-
you must show your code and what you have worked on before asking others to help you. Please post your code. – grepit Jun 12 '13 at 17:05
-
So, to start, do you know the exact position and length of the substring you are trying to replace? Or just know what is in the substring and have to find it first? – Humungus Jun 12 '13 at 17:05
-
or String.replaceAll? – greedybuddha Jun 12 '13 at 17:05
-
USE GOOGLE.... http://stackoverflow.com/questions/12734721/using-string-replace-in-java – Kickaha Jun 12 '13 at 17:06
3 Answers
For replacing any thing java.lang.String class provides three replace method which are
String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.String replaceAll(String regex, String replacement)
Replaces each substring of this string that matches the given regular expression with the given replacement.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.

- 1,548
- 17
- 23
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.

- 127,459
- 24
- 238
- 287