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);
}
}
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);
}
}
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);
}
}
Output: Replace new text