Java String replace() Method

The String.replace() method in Java is used to replace occurrences of a specified character or substring with another character or substring within a string.

Table of Contents

  1. Introduction
  2. replace Method Syntax
  3. Examples
    • Replacing Characters
    • Replacing Substrings
    • Handling Edge Cases
    • Real-World Use Case
  4. Conclusion

Introduction

The String.replace() method is a member of the String class in Java. It allows you to replace all occurrences of a specified character or substring within a string with another character or substring. This method is useful for string manipulation tasks, such as formatting and data cleaning.

replace() Method Syntax

The syntax for the replace method is as follows:

Replacing Characters

public String replace(char oldChar, char newChar)

Replacing Substrings

public String replace(CharSequence target, CharSequence replacement)

Examples

Replacing Characters

The replace method can be used to replace all occurrences of a specified character with another character.

Example

public class ReplaceCharExample {
    public static void main(String[] args) {
        String str = "Hello World";
        String newStr = str.replace('o', 'a');
        System.out.println("Original string: " + str);
        System.out.println("Replaced string: " + newStr);
    }
}

Output:

Original string: Hello World
Replaced string: Hella Warld

Replacing Substrings

The replace method can be used to replace all occurrences of a specified substring with another substring.

Example

public class ReplaceSubstringExample {
    public static void main(String[] args) {
        String str = "Hello World";
        String newStr = str.replace("World", "Java");
        System.out.println("Original string: " + str);
        System.out.println("Replaced string: " + newStr);
    }
}

Output:

Original string: Hello World
Replaced string: Hello Java

Handling Edge Cases

Example: Replacing Non-Existent Characters or Substrings

If the character or substring to be replaced is not found in the string, the original string is returned unchanged.

public class ReplaceNotFoundExample {
    public static void main(String[] args) {
        String str = "Hello World";
        String newStr = str.replace('x', 'y');
        System.out.println("Original string: " + str);
        System.out.println("Replaced string: " + newStr);
    }
}

Output:

Original string: Hello World
Replaced string: Hello World

Example: Replacing with an Empty String

Replacing a character or substring with an empty string effectively removes the character or substring from the string.

public class ReplaceWithEmptyExample {
    public static void main(String[] args) {
        String str = "Hello World";
        String newStr = str.replace("World", "");
        System.out.println("Original string: " + str);
        System.out.println("Replaced string: " + newStr);
    }
}

Output:

Original string: Hello World
Replaced string: Hello

Real-World Use Case

Example: Formatting Phone Numbers

One common use case for replace is formatting phone numbers by removing unwanted characters.

public class FormatPhoneNumberExample {
    public static void main(String[] args) {
        String phoneNumber = "(123) 456-7890";
        String formattedNumber = phoneNumber.replace("(", "")
                                            .replace(")", "")
                                            .replace(" ", "")
                                            .replace("-", "");
        System.out.println("Original phone number: " + phoneNumber);
        System.out.println("Formatted phone number: " + formattedNumber);
    }
}

Output:

Original phone number: (123) 456-7890
Formatted phone number: 1234567890

In this example, the replace method is used to remove unwanted characters from a phone number to create a standardized format.

Conclusion

The String.replace() method in Java is a versatile tool for replacing characters and substrings within a string. It provides a simple way to perform string manipulations, making it useful for tasks such as formatting and data cleaning. By understanding and utilizing the replace method, you can efficiently manage string replacements in your Java programs.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top