How to replace word in java

Java has in built method to replace word from text string. Java provides two methods replace() and replaceAll().

1. replace() will replace a word in single occurrence.

2. replaceAll() will replace all words from the string.

3. replaceFirst() will replace first word from the string

Example of replace all word from text

public class ReplaceAll {

    public static void main(String[] args) {
        String str="We want replace replace word from this string";

        str=str.replaceAll("replace", "Done");

        System.out.println(str);
    }
}

Output of replace word

We want Done word from this string

If you want to replace single word from text string you can use replace() method instead of replaceAll() method

  str=str.replace("replace", "Done");

Output of replace word

We want Done Done word from this string

replaceFirst() method will replace first word of the string

  str=str.replaceFirst("replace", "Done");

Output of replace word

We want Done replace word from this string
Bookmark  

 

Leave a Reply

Security Code:

 

  Random Post