To delete a character from a string in Java, you can use the substring
method of the String
class.
The substring
method takes two arguments: a start index and an end index. It returns a new string that is a substring of the original string, starting at the specified start index and ending at the specified end index. The original string is not modified.
For example, consider the following string:
String str = "Hello, world!";
To delete the character at index 5 (the comma), you can use the substring
method as follows:
String newStr = str.substring(0, 5) + str.substring(6);
This will create a new string that is the concatenation of the substrings of str
before and after the character at index 5. The resulting string will be "Hello world!".
You can also use the StringBuilder
class to delete a character from a string. The StringBuilder
class has a deleteCharAt
method that removes the character at the specified index.
For example:
StringBuilder sb = new StringBuilder(str); sb.deleteCharAt(5); String newStr = sb.toString();
This will delete the character at index 5 from the StringBuilder
and return the resulting string using the toString
method.
Note that the substring
and deleteCharAt
methods are zero-based, meaning that the first character of the string is at index 0, the second character is at index 1, and so on.
Here's an example of a complete program that deletes a character from a string:
public class Main { public static void main(String[] args) { String str = "Hello, world!"; String newStr = str.substring(0, 5) + str.substring(6); System.out.println(newStr); // Output: "Hello world!" } }
This will print "Hello world!" to the console.