In this example we shall explain the replaceAll() method in the String class. With the replaceAll() method we can replace the whole or part of the string or character sequences. String objects are immutable and cannot be changed the value. When ever you change the value, new string object is created. This method also creates the new object after replacing the values and return the new object. Lets look at the below example to understand this concept better. Some of the operations you can do using the replaceAll() method is:
- You can replace the single character
- You can replace the sequence of characters or a word
- You can replace using the regular expression
StringReplaceExample.java
package javabeat.net.core; /** * String replaceAll() method example * @author krishna * */ public class StringReplaceExample { public static void main(String args[]){ String str = "String replaceAll() method example!!"; String strRegExTest = "Java 12 23 String 4 Replace Example"; String strObj = null; // Replace all occurrences of "t" to "T" strObj = str.replaceAll("t", "T"); System.out.println(strObj); // Remove all occurrences of "!" strObj = str.replaceAll("!", ""); System.out.println(strObj); // Replace "example" to "Example" strObj = str.replaceAll("example", "Example"); System.out.println(strObj); // Remove all the numbers strObj = strRegExTest.replaceAll("[0-9]+", ""); System.out.println(strObj); // Replace all the words to "Word" strObj = strRegExTest.replaceAll("[a-zA-Z]+", "Word"); System.out.println(strObj); } }
Output…
STring replaceAll() meThod example!! String replaceAll() method example String replaceAll() method Example!! Java String Replace Example Word 12 23 Word 4 Word Word