Skip to content

Instantly share code, notes, and snippets.

@muhdkhokhar
Created January 7, 2025 15:59
Show Gist options
  • Save muhdkhokhar/5d9cc39d11069db2496a8ef192325e98 to your computer and use it in GitHub Desktop.
Save muhdkhokhar/5d9cc39d11069db2496a8ef192325e98 to your computer and use it in GitHub Desktop.
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