Home >Java >javaTutorial >How to use replace function in java
The replace() function in Java is used to replace characters or substrings in a string. There are two forms: replacing all matching characters and replacing a specific number of matching characters. Returns a new string after replacement, the original string is unaffected. Parameters include: characters/substrings to replace, characters/substrings to replace, and (optional) the maximum number of times to replace.
Usage of replace() function in Java
replace()
in Java Function used to replace characters or substrings in a string. It has two forms:
1. Replace all matching characters
<code class="java">String result = string.replace('a', 'b');</code>
In this example, all 'a's in string
characters will be replaced with 'b'.
2. Replace a specific number of matching characters
<code class="java">String result = string.replace('a', 'b', 2);</code>
In this example, the first two 'a' characters in string
will be Replace with 'b'. If the specified value is less than 0, all matching characters are replaced.
Usage:
Parameters:
oldChar/oldString
: The character or substring to be replaced. newChar/newString
: Replaced character or substring. (optional) max
: The maximum number of times to replace, default is all matches. <code class="java">String s = "Hello World!"; // 替换所有 'o' 为 'e' System.out.println(s.replace('o', 'e')); // 替换前两个 'l' 为 'x' System.out.println(s.replace('l', 'x', 2)); // 替换 "World" 为 "Universe" System.out.println(s.replace("World", "Universe"));</code>
Output:
<code>Helle Werld! Hexplo Werld! Hello Universe!</code>
The above is the detailed content of How to use replace function in java. For more information, please follow other related articles on the PHP Chinese website!