Question:
How to replace word in java?
Answer:
Java has built in methods to replace words from text string.
replace() will replace a word in single occurrence.
replaceAll() will replace all words from the string.
replaceFirst() will replace first word from the string
replace() will replace a word in single occurrence.
replaceAll() will replace all words from the string.
replaceFirst() will replace first word from the string
Code:
public class ReplaceWords { public static void main(String[] args) { String str="I do not like green eggs or green ham."; System.out.println(str); str=str.replaceAll("green", "blue"); System.out.println(str); } }
Output:
$ java ReplaceWords I do not like green eggs or green ham. I do not like blue eggs or blue ham.