Replacement in a String

Java-Replacement in a String

Replace Method

If you want to replace all occurrences of one character or character sequence in the invoking string with another character or character sequence use the replace() method. The replace( ) method has two forms:

Replacement in a String

In the first form, oldChar specifies the character to be replaced by the character specified by newChar. The resulting string is returned. For example:

Replacement in a String

The second form of replace( ) replaces one character sequence with another. The ‘target’ specifies the CharSequence to be replaced by the CharSequence specified by ‘replacement’. The resulting string is returned. For example:

Replacement in a String

ReplaceAll Method

The replaceAll( ) method enables us to replace all occurrence of substring with another substring. The capability of replaceAll( ) makes the complex search of substrings possible within a string object. After a search, each matched substring is replaced with the given replacement. For example:

Replacement in a String


ReplaceFirst Method

The replaceFirst( ) method enables us to replace first occurrence of substring with another substring. For example:

Replacement in a String


Program

Replacement in a String

Program Source

public class Javaapp {

    public static void main(String[] args) {

        String str = "A1D,A23D,A456D,A7897D,ABCD";
        String str2 = str.replaceAll("[0-9]+", "BC");
        String str3 = str.replaceFirst("[0-9]+", "BC");
        
        System.out.println("str -> "+str);
        System.out.println("str2-> "+str2);
        System.out.println("str3-> "+str3);
    }
}

Leave a Comment