Ticker

6/recent/ticker-posts

Java String replace() Method — Learn with Example

Java String replace() Method — Learn with Example

Introduction

The replace() method in Java is a part of the String class, used to replace occurrences of a specified character or substring with another character or substring within a given string. This method provides a convenient way to modify strings without directly manipulating the character array.

Syntax

The syntax of the replace() method is as follows:

java
public String replace(char oldChar, char newChar)
public String replace(CharSequence target, CharSequence replacement)

Parameters:

  • oldChar: The character to be replaced.
  • newChar: The character to replace the old character with.
  • target: The substring to be replaced.
  • replacement: The substring that will replace the target.

Return Type:

The replace() method returns a new string with the specified replacements.

Examples

Example 1: Replacing Characters

In this example, we will replace occurrences of a specific character in a given string.

java
public class ReplaceExample {
public static void main(String[] args) {
String originalString = "Hello, world!";
char oldChar = 'o';
char newChar = 'x';

String replacedString = originalString.replace(oldChar, newChar);

System.out.println("Original String: " + originalString);
System.out.println("Replaced String: " + replacedString);
}
}

Output:

arduino
Original String: Hello, world!
Replaced String: Hellx, wxrld!

Example 2: Replacing Substrings

In this example, we will replace a substring with another substring in a given string.

java
public class ReplaceExample {
public static void main(String[] args) {
String originalString = "The sun sets in the west.";
String target = "west";
String replacement = "east";

String replacedString = originalString.replace(target, replacement);

System.out.println("Original String: " + originalString);
System.out.println("Replaced String: " + replacedString);
}
}

Output:

arduino
Original String: The sun sets in the west.
Replaced String: The sun sets in the east.

Explanation

  • In Example 1, we create a String named originalString with the value "Hello, world!". We then use the replace() method to replace all occurrences of the character 'o' with the character 'x'. The result is stored in the replacedString variable, which becomes "Hellx, wxrld!".

  • In Example 2, we create a String named originalString with the value "The sun sets in the west.". We use the replace() method to replace all occurrences of the substring "west" with the substring "east". The result is stored in the replacedString variable, which becomes "The sun sets in the east.".

The replace() method is useful for tasks such as data cleaning, text manipulation, and string formatting in Java.

Post a Comment

0 Comments