Java string replace() method explained
It is a predefined function which is present in the Java.lang.String package. It is used to replace a character or sequence of characters with the new character or sequence of characters. It is of two types let's discuss each of them in detail-
Types of replace() methods of String class
public String replace(CharSequence target, CharSequence replacement) {}
public String replace(char oldChar, char newChar) {}
1. replace(CharSequence target, CharSequence replacement): This method takes the target string(string you want to change) and replacement string(by which you will change your target string) and replace the target string with the replacement string and then returns the resulted string let's see it's implementation-
Example 01 of replace(CharSequence target, CharSequence replacement) function
public class Replace {
public static void main(String a[]) { //it is your choice to give parameter like this
String s = new String("marvel");
System.out.println(s.replace("m","b"));
}
}
Output:
barvel
Example 02 of replace(CharSequence target, CharSequence replacement) function
public class Replace {
public static void main(String a[]) {//it is your choice to give parameter like this
String s = new String("The falcon and the winter soldier finally released");
System.out.println(s.replace("l","t"));
//replace all occurences of l with t in a string
}
}
Output:
The fatcon and the winter sotdier finatty reteased
2. replace(char oldChar, char newChar): This method takes the first parameter, the character which is to be replaced and the second parameter takes the character by which you will replace the old character, let's see it's implementation-
Example 01 of replace(char oldChar, char newChar) function
public class Replace {
public static void main(String a[]) {//it is your choice to give parameter like this
String s = new String("marvel movies are awesome");
System.out.println(s.replace('m','b'));
//replace all occurences of m with b in a string
}
}
barvel bovies are awesobe
Hello, visitor your comments are so helpful for us so do not hesitate just write the comment we read all your comments so don't think your comment goes waste.