Home >Java >javaTutorial >How Can I Replace Substrings in Java Using the `replace` Method?

How Can I Replace Substrings in Java Using the `replace` Method?

DDD
DDDOriginal
2024-12-14 18:11:12851browse

How Can I Replace Substrings in Java Using the `replace` Method?

Replacing Strings in Java

Replacing a specific substring with another string in Java can be easily achieved using the replace method. This method takes two arguments: the substring to be replaced and the replacement string.

Example #1: Replacing "HelloBrother" with "Brother"

To replace the substring "HelloBrother" with "Brother", you can use the following code:

String replacedString = someString.replace("HelloBrother", "Brother");

Example #2: Replacing "JAVAISBEST" with "BEST"

Similarly, to replace the substring "JAVAISBEST" with "BEST", you can use the following code:

String replacedString = someString.replace("JAVAISBEST", "BEST");

The replace method returns a new string with the substring replaced. The original string remains unmodified.

The above is the detailed content of How Can I Replace Substrings in Java Using the `replace` Method?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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