Java String Replace Sample Code

The Java String class has three replace methods to manipulate a string. We have replace(), replaceAll(), and replaceFirst() methods to accomplish the replace of characters or strings within a string.

The String.replace(arg1, arg2) method will return a new string resulting from replacing all occurrences of character arg1 with character arg2.

The String.replaceAll(arg1, arg2) method will replace each substring of the string arg1 that matches the given regular expression of string arg2.

The String.replaceFirst(arg1, arg2) method will replace the first substring of arg1 that matches the given regular expression with the given replacement of arg2.

Java String Replace Source Code

package com.jcd.java.tutorials;

public class JavaStringReplace 
{

	public static void main(String[] args) 
	{
		
		String replaceString = "My Really Cool Sample String";
		System.out.println("\nOriginal String: "+replaceString);
		
		//String replace() method using single characters
		System.out.println("\nReplace M with m: "+replaceString.replace('M', 'm'));
		System.out.println("Replace S with s: "+replaceString.replace('S', 's'));
		
		System.out.println("\n-----------------------------------------------");
		
		String replaceAllString = "My Really Cool Sample Cool String My";
		System.out.println("\nOriginal String: "+replaceAllString);
		
		//String replaceAll() method using strings to replace all occurrences
		System.out.println("\nReplace My with Your: "+replaceAllString.replaceAll("My", "Your"));
		System.out.println("Replace Cool with Awesome: "+replaceAllString.replaceAll("Cool", "Awesome"));
		
		System.out.println("\n-----------------------------------------------");
		
		String replaceFirstString = "First Thing You Need To Do First";
		System.out.println("\nOriginal String: "+replaceFirstString);
		
		//String replaceFirst() method to replace first occurrence 
		System.out.println("\nReplace First with Second: "+replaceFirstString.replaceFirst("First", "Second"));
	
	}
}


Sample Java String Replace Output


Original String: My Really Cool Sample String

Replace M with m: my Really Cool Sample String
Replace S with s: My Really Cool sample string

-----------------------------------------------

Original String: My Really Cool Sample Cool String My

Replace My with Your: Your Really Cool Sample Cool String Your
Replace Cool with Awesome: My Really Awesome Sample Awesome String My

-----------------------------------------------

Original String: First Thing You Need To Do First

Replace First with Second: Second Thing You Need To Do First



Java References:

Add a Comment

Your email address will not be published. Required fields are marked *