The difference between replace and replaceAll in JAVA

1.The parameters of replace are char and CharSequence, which can support the replacement of characters and the replacement of strings (CharSequence is the meaning of string sequence, which is a string in
plain terms ); 2.The parameter of replaceAll is regex or char, That is, the replacement based on regular expressions, for example, you can use replaceAll("\\d", "*") to replace all numeric characters in a string with asterisks;

The same point is that all replace, that is, a certain character or character string in the source string is replaced with a specified character or character string.

If you only want to replace the first occurrence, you can use replaceFirst(). This method is also based on regular expression replacement, but when it is different from replaceAll(), only the first occurrence of the string is replaced;

In addition, if the parameter data used by replaceAll() and replaceFirst() is not based on regular expressions, the effect of replacing strings with replace() is the same, that is, the two also support string operations;

For example:

public class ReplaceChar {
    public static void main(String[] args) {
        String strTmp = new String("BBBBBBBYYYYYYY");
        strTmp = strTmp.replaceAll ("\\D", "Y"); 
        System.out.println(strTmp);
        strTmp = strTmp.replaceAll ("Y", "N"); 
        System.out.println(strTmp);
        strTmp = strTmp.replace("N", "C");
        System.out.println(strTmp);
        strTmp = strTmp.replaceFirst("\\D", "q");
        System.out.println(strTmp);
    }
}

The results are as follows:

YYYYYYYYYYYYYYY
NNNNNNNNNNNNNNN
CCCCCCCCCCCCCCC
qCCCCCCCCCCCCCC

 

 

Guess you like

Origin blog.csdn.net/johnt25/article/details/86175268