** Replace string **
The replace method searches the target character string for the character string specified by the first argument, and replaces the matched character string with the character string specified by the second argument. Then, the replaced character string is returned as a return value. String replacement starts at the beginning and continues to the end of the string.
Simply put, ** replace the character string specified by the first argument with the character string specified by the second argument **.
String class methods java.lang.String.replace()
Target string.replace(String to be replaced,Replacement string)
Example
public static void main(String[] args) {
//Target string
String strBefore = "Hello world!";
//String to be replaced"Hello"Replace string"Goodbye"Replace with
String strAfter = strBefore.replace("Hello", "Goodbye");
System.out.println(strAfter);
}
Execution result
Goodbye world!
If there are multiple parts to be replaced, all the corresponding parts are replaced.
public static void main(String[] args) {
// //Target string
String strBefore = "aabbaacc aab ";
// "aa"→"DDD"Replace with
String strAfter = strBefore.replace("aa", "DDD");
System.out.println(strAfter);
}
Execution result
DDDbbDDDcc DDDb
In the example below, the first AAA and the next AAA are replaced with B. Therefore, it does not become AABB or ABBA.
public static void main(String[] args) {
//8 strings A before replacement
String strBefore = "AAAAAAAA";
// "AAA"→"B"Replace with
String strAfter = strBefore.replace("AAA", "B");
System.out.println(strAfter);
}
Execution result
BBAA
The replace method is overloaded, and some receive two ** char ** arguments and some receive two ** CharSequence ** arguments. Note that there is no overload that accepts mixed arguments of char and CharSequence types.
Recommended Posts