• Register

Java Str has 3 kinds of Replace method

1.   replace

2.   replaceAll

3.   replaceFirst.

With the assistance of these you can substitute char in your str. Let us see each in details:

Java Str replace() Function

Java String replace() function substitutes every incidence of a particular char with a new char and yields a new str. This function permits the subtitute of a order of char values.

Syntax:

public Str1 replace(char oldC1, char newC1)

Parameters:

oldCh1 − old char.

newCh1 − new char.

Yield Value:

This method returns a str by substituting oldCh1 with newCh1.

Example:

public class Kodlogs {
    public static void main(String args1[]) {
        String S11 = new String("the quick fox jumped over a lazy dog");
        System.out.println("Original String is given as ': " + S1);
        System.out.println("Str after substituting 'fox' with 'dog': " + S1.replace("fox", "dog"));
        System.out.println("Str after substituting all 't' with 'a': " + S1.replace('t', 'a'));

    }
}

OutCome:

Unique Str is ': the quick fox jumped
Str afterward substituting 'fox' with 'dog': the quick dog jumped
Str afterward substituting all 't' with 'a': ahe quick fox jumped

Java Str Replaceall()

Java Str replaceAll() function discovers all incidences of order of characters identical a ordered expression and replaces them with the substitution of str. At the conclusion of call, a new str is returned by the method.

Signature:

public Str1 replaceAll(String regex1, String replacement1) 

Parameters:

Regx1: regular exp

replacement: replacement order of char

Example:

public class Guru99Ex2 {
    public static void main(String args1[]) {
        String str1 = "kodlogs is a website giving  tutorials";
        //eradicate white spaces
        String str21 = str21.replaceAll("\\s", "");
        System.out.println(str21);
    }
}

Output:

kodlogsisawebsitegivingtutorials

2,760 points
7 4