Home > Java > javaTutorial > How to use replace function in java

How to use replace function in java

下次还敢
Release: 2024-05-08 03:27:17
Original
539 people have browsed it

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.

How to use replace function in java

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>
Copy after login

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>
Copy after login

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:

  • Return type: A new string after replacement, the original string is not affected.
  • 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.
  • Example:
<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>
Copy after login

Output:

<code>Helle Werld!
Hexplo Werld!
Hello Universe!</code>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template