Created
January 7, 2025 15:59
-
-
Save muhdkhokhar/5d9cc39d11069db2496a8ef192325e98 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class StringReplaceByIndex { | |
public static void main(String[] args) { | |
String original = "Hello, World!"; | |
int startIndex = 7; // starting index of the substring to replace | |
int endIndex = 12; // ending index (exclusive) of the substring to replace | |
String replacement = "Java"; | |
String result = replaceSubstring(original, startIndex, endIndex, replacement); | |
System.out.println(result); // Output: Hello, Java! | |
} | |
public static String replaceSubstring(String str, int startIndex, int endIndex, String replacement) { | |
if (str == null || replacement == null) { | |
throw new IllegalArgumentException("String and replacement cannot be null"); | |
} | |
if (startIndex < 0 || endIndex > str.length() || startIndex > endIndex) { | |
throw new IllegalArgumentException("Invalid start or end index"); | |
} | |
return str.substring(0, startIndex) + replacement + str.substring(endIndex); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment