How to remove single character from a String by index
To remove a single character from a string by its index in Java, you can use the StringBuilder.deleteCharAt()
method. Here's an example of how to use it:
String str = "Hello World!";
StringBuilder sb = new StringBuilder(str);
sb.deleteCharAt(5);
String newStr = sb.toString();
This will remove the character at index 5 of the string "Hello World!", which is the space character. The resulting string will be "HelloWorld!".
Alternatively, you can use the substring()
method of the String
class to create a new string that does not include the character at the specified index. Here's an example:
String str = "Hello World!";
String newStr = str.substring(0, 5) + str.substring(6);
This will create a new string by concatenating two substrings of the original string: one from the beginning of the string up to the character at index 5 (exclusive), and another from the character at index 6 (inclusive) to the end of the string.
Note that both of these methods will modify the string in place and return a new string. The original string will not be modified.