To delete the last character of a string in Java, you can use the substring()
method. This method returns a new string that is a substring of the original string. You can specify the starting index and the ending index of the substring you want to extract. To delete the last character, you can specify the starting index as 0 and the ending index as the length of the string minus 1.
Here's an example of how to use the substring()
method to delete the last character of a string:
String str = "Hello World"; // Delete the last character of the string str = str.substring(0, str.length() - 1); System.out.println(str); // Output: "Hello Worl"
Alternatively, you can use the StringBuilder
class to delete the last character of a string. The StringBuilder
class provides a mutable (modifiable) string representation that you can use to append, delete, or modify characters in a string.
To delete the last character of a string using the StringBuilder
class, you can use the deleteCharAt()
method and pass it the index of the character you want to delete. The index of the last character in the string is length() - 1
.
Here's an example of how to use the StringBuilder
class to delete the last character of a string:
String str = "Hello World"; // Create a StringBuilder object from the string StringBuilder sb = new StringBuilder(str); // Delete the last character sb.deleteCharAt(sb.length() - 1); // Convert the StringBuilder object back to a string str = sb.toString(); System.out.println(str); // Output: "Hello Worl"