A PHP Error was encountered

Severity: 8192

Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated

Filename: libraries/Filtered_db.php

Line Number: 23

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

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

0

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.

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Consider the program:

Here, we have two strings str1 and str2str2 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!

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now