Replace a character at a specific index in a string?
To replace a character at a specific index in a string in Java, you can use the substring()
method of the java.lang.String
class to extract the part of the string before the character you want to replace, the charAt()
method to get the character at the specified index, and the concat()
method to concatenate the modified string with the part of the original string after the character you want to replace.
Here is an example of how you can use these methods to replace a character at a specific index in a string:
public class StringReplaceExample {
public static void main(String[] args) {
String str = "Hello, world!";
int index = 7;
char ch = 'J';
String result = str.substring(0, index) + ch + str.substring(index+1);
System.out.println(result);
}
}
This example replaces the character at index 7 (the character 'w') in the string "Hello, world!" with the character 'J', and prints the resulting string "Hello, Jorld!".
Note that in this example, the index of the first character in the string is 0. If you want to replace the character at the last index in the string, you can use the length()
method to get the length of the string, and use this value as the index.
For example, to replace the last character in the string "Hello, world!", you can do the following:
public class StringReplaceExample {
public static void main(String[] args) {
String str = "Hello, world!";
int index = str.length() - 1;
char ch = 'J';
String result = str.substring(0, index) + ch + str.substring(index+1);
System.out.println(result);
}
}
This example replaces the last character in the string "Hello, world!" with the character 'J', and prints the resulting string "Hello, worlJ!".