Replace a sub-string in a string in Java

Understanding String Manipulation

Replacing a sub-string in a string means finding a specific sequence of characters and replacing it with another sequence.

We will explore three different methods to achieve this in Java.

Method 1: Using Loop

This method iterates through the string and replaces occurrences of the sub-string.

public class ReplaceSubstring {
    public static String replaceSubstring(String str, String oldWord, String newWord) {
        return str.replaceAll(oldWord, newWord);
    }

    public static void main(String[] args) {
        String str = "Hello World!";
        str = replaceSubstring(str, "World", "Java");
        System.out.println("Modified String: " + str);
    }
}
            
Input: Hello World!
Output: Hello Java!

Method 2: Using Recursion

This method replaces the sub-string recursively.

public class ReplaceRecursive {
    public static String replaceRecursive(String str, String oldWord, String newWord) {
        if (!str.contains(oldWord)) {
            return str;
        }
        return replaceRecursive(str.replaceFirst(oldWord, newWord), oldWord, newWord);
    }

    public static void main(String[] args) {
        String str = "I love programming";
        str = replaceRecursive(str, "love", "enjoy");
        System.out.println("Modified String: " + str);
    }
}
            
Input: I love programming
Output: I enjoy programming

Method 3: Using String Functions

This method uses Java's built-in replace() function.

public class ReplaceUsingFunctions {
    public static void main(String[] args) {
        String str = "Replace old text";
        str = str.replace("old", "new");
        System.out.println("Modified String: " + str);
    }
}
            
Input: Replace old text
Output: Replace new text
Strings

Below You will find some of the most important codes in languages like C, C++, Java, and Python. These codes are of prime importance for college semester exams and online tests.

Getting Started

Check whether a character is a vowel or consonant: C C++ Java Python

Check whether a character is an alphabet or not: C C++ Java Python

Find the ASCII value of a character: C C++ Java Python

Length of the string without using strlen() function: C C++ Java Python

Toggle each character in a string: C C++ Java Python

Count the number of vowels: C C++ Java Python

Remove the vowels from a string: C C++ Java Python

Check if the given string is Palindrome or not: C C++ Java Python

Print the given string in reverse order: C C++ Java Python

Remove all characters from string except alphabets: C C++ Java Python

Remove spaces from a string: C C++ Java Python

Replace a sub-string in a string: C C++ Java Python

Count common sub-sequences in two strings: C C++ Java Python

Compare two strings with wildcard support in one of them: C C++ Java Python

List all permutations of a given string in dictionary order: C C++ Java Python

Operations on Strings: C C++ Java Python