How to replace the occurrences of a substring in a given String using the Java replace() , replaceAl

Published: 02 June 2020
on channel: Career & Tech HQ
912
6

How to replace the occurrences of a substring in a given String using the Java replace() , replaceAll() and replaceFirst() methods

In this video, we will discuss on the Java replace() method, which is used for replacing parts of a String with another String or a character with another character. The replace() method returns a String, and it has three variations that we are going to look at, by taking concrete examples

1. In the first example, I will show you how the replace all the occurrences of parts of a String with another String using the replace() method

String str = “my string this is my string”;
System.out.println(str.replace(“string” , “name”));

We can also replace a character type value with another character like this
System.out.println(str.replace(‘m’ , ‘b’));

2. In the second example, I will show you how to replace all the occurrences of a substring or a character with another String using the replaceAll() method
String str = “my string this is my string”;
System.out.println(str.replaceAll(“string” , “name”));

Note that the replaceAll() metho replaces all the occurrences of the substring with the new specified String

Also, unlike the replace() method, the replaceAll() method returns an error when we want to replace character type values
System.out.println(str.replaceFirst(‘y’ , ‘e’));
Will return an error

3. In the third example, I will show you how to replace the first occurrence of a substring with another String using the replaceFirst() method

String str = “my string this is my string”;
System.out.println(str.replaceFirst(“string” , “name”));

Note that, only the first substring has changed
Also, the replaceFirst() method does not work when trying to replace character type values
System.out.println(str.replaceFirst(‘y’ , ‘e’));
Will return an error

#codingriver
#java
#programming


On this page of the site you can watch the video online How to replace the occurrences of a substring in a given String using the Java replace() , replaceAl with a duration of hours minute second in good quality, which was uploaded by the user Career & Tech HQ 02 June 2020, share the link with friends and acquaintances, this video has already been watched 912 times on youtube and it was liked by 6 viewers. Enjoy your viewing!