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:
In the first form, oldChar specifies the character to be replaced by the character specified by newChar. The resulting string is returned. For example:
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:
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:
ReplaceFirst Method
The replaceFirst( ) method enables us to replace first occurrence of substring with another substring. For example:
Program
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); } }