Appearance
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:
java
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:
java
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 Java String objects are immutable, so neither method modifies the original string. StringBuilder.deleteCharAt() modifies the StringBuilder instance in place, while substring() creates a new String object.
Warning: Ensure the specified index is within the valid range (0 to length() - 1). Otherwise, both methods will throw an IndexOutOfBoundsException.