How to Replace Character Or Substring of Java String


In this example, we will write an example to replace character or substring by new one using replace method of java String class.

Source Code

package com.beginner.examples;

public class StringReplace {

	public static void main(String[] args) {
		
		//Create String.
		String string = "Hello World";
		
		/*
		 * To replace a specified character with new character use 
		 * the method replace(int oldChar, int newChar) of Java String.
		 */
		System.out.println(string.replace( 'H','A' ));
		
		/*
		 * To replace the first substring of this string that matches the given regular expression
		 * use the method replaceFirst(String regularExpression, String newString) of Java String.
		 */
		System.out.println(string.replaceFirst("o", "x"));
		
		/*
		 * To replace the each substring of this string that matches the given regular expression
		 * use the method replaceAll(String regex, String replacement) of Java String.
		 */
		System.out.println(string.replaceAll("o", "x"));

	}

}

Output:

Aello World
Hellx World
Hellx Wxrld
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments