A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://howtodoinjava.com/java/string/java-string-replace-method/ below:

Replace All Occurrences in Text

The String.replace() API searches for a literal substring and replaces each occurrence with the replacement string. The search for substring starts from the beginning of the string i.e. index 0.

Note that a similar method String.replaceAll() searches and replaces all substrings using regular expressions.

1. String.replace() Method

The replace() method is an overloaded method and comes in two versions:

public String replace(char oldChar, char newChar);

public String replace(CharSequence target, CharSequence replacement);
2. Replace All Occurrences of a Character

The following Java program replaces all occurrences of the letter ‘o’ (lower case) with the letter ‘O’ (upper case).

String message = "Hello world !!";

Assertions.assertEquals("HellO wOrld !!", message.replace('o', 'O'));
3. Replace All Occurrences of a Substring

The following Java program replaces all occurrences of the substring “Hello” with the new String “Hi”.

String message = "Hello world !!";

Assertions.assertEquals("Hi world !!", message.replace("Hello", "Hi"));
4. Regex is Not Supported

Regular expressions are not allowed as method arguments. If we use a regex pattern, it will be treated as a literal string.

In the following program, the regex [H] pattern will match character H is regex is supported. But replace() does not support regex so there are no matches found.

String message = "Hello world !!";

Assertions.assertEquals("Hello world !!", message.replace("[H]", "h"));
5. Null is Not Allowed

The 'null' is not allowed as both method arguments. It will throw NullPointerException.

Assertions.assertThrows(NullPointerException.class, () -> {
  message.replace(null, "O");
});

Assertions.assertThrows(NullPointerException.class, () -> {
  message.replace("o", null);
});

Happy Learning !!

References:
Java String Doc


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4