String

String replace method

With this example we are going to demonstrate how to use the replace method of String class. The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class. In short, to replace a String you should:

  • Create a new String.
  • Use replace(char oldChar, char newChar) API method. This method returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
  • Use replaceFirst(String regex, String replacement) API method. It replaces the first substring of this string that matches the given regular expression with the given replacement.
  • Use replaceAll(String regex, String replacement) API method. It replaces each substring of this string that matches the given regular expression with the given replacement.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;

public class StringReplaceMethod {
	
	public static void main(String[] args) {
		
		String s = "Java Code Geeks - Java Examples";
		
		// replace all occurrences of given character with new one
		System.out.println(s.replace('e','i'));
		 
		// replace only first occurrence of given string
		System.out.println(s.replaceFirst("Ja", "Je"));
		 
		// replace all occurrence of given string
		System.out.println(s.replaceAll("Ja", "Je") );
		
	}

}

Output:

Java Codi Giiks - Java Examplis
Jeva Code Geeks - Java Examples
Jeva Code Geeks - Jeva Examples

 
This was an example of how to use the replace method of String class in Java.

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions

 

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button