Delete the last two characters of the String in java

Delete the last two characters of the String in java

To delete the last two characters of a String in Java, you can use the substring method to create a new String without those characters. Here's how you can do it:

public class DeleteLastTwoCharacters { public static void main(String[] args) { String originalString = "HelloWorld"; // Check if the string has at least 2 characters before deleting if (originalString.length() >= 2) { String stringWithoutLastTwo = originalString.substring(0, originalString.length() - 2); System.out.println("Original String: " + originalString); System.out.println("String without last two characters: " + stringWithoutLastTwo); } else { System.out.println("String is too short to delete the last two characters."); } } } 

In this example:

  1. We first check if the originalString has at least 2 characters to avoid an IndexOutOfBoundsException.

  2. If the string has at least 2 characters, we use the substring method to create a new String from the beginning of the original string to the length minus 2 characters. This effectively removes the last two characters.

  3. We print both the original string and the modified string without the last two characters.

Keep in mind that substring creates a new String, so it does not modify the original string. If the original string has fewer than 2 characters, you should handle this case appropriately based on your requirements.


More Tags

android-2.2-froyo extjs compression pygame-clock phpmailer emoticons asp.net-membership sapply pip tokenize

More Java Questions

More Retirement Calculators

More Biology Calculators

More Investment Calculators

More Other animals Calculators