ADVERTISEMENT
ADVERTISEMENT

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 »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.