×

Java Programs

Java Practice

How to replace string with another string in java using String.replace() method?

In this program, we will learn how to replace a string with another string using String.replace() method of String class in Java?

Give two strings and we have to replace one string with second using String.replace() method in Java?

String.replace()

This is a predefined (built-in) method of String class in java, it returns replaced (new) string.

Consider the program:

Here, we have two strings str1 and str2, str2 will be replaced with str1 and finally, str1 is the replaced string (which will be returned through the function).

//Java Program to replace a string with new one.

public class JavaStringReplacePrg
{
	public static void main(String args[])
	{
		//string 1
		String str1="www.includehelp.com";
		//string 2
		String str2="Hello World!";

		//printing strings before replacing
		System.out.println("\nStrings before replacing:");
		System.out.println("str1: "+str1 +"\nstr2:" + str2);
		
		//replacing string str1 with str2
		str1=str1.replace(str1, str2);

		//printing strings after replacing
		System.out.println("\nStrings after replacing:");
		System.out.println("str1: "+str1 +"\nstr2:" + str2);
	}
}

Output

Strings before replacing:
str1: www.includehelp.com
str2:Hello World!

Strings after replacing:
str1: Hello World!
str2:Hello World!

Java String Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.