Remove the last chars of the Java String variable

Remove the last chars of the Java String variable

To remove the last characters from a Java String variable, you can use the substring method or use the StringBuilder class to create a new String with the characters removed. Here are both approaches:

  1. Using substring method:

    You can use the substring method to create a new String that excludes the last characters of the original String. Here's an example:

    String originalString = "Hello, World!"; int charactersToRemove = 3; // Number of characters to remove from the end String resultString = originalString.substring(0, originalString.length() - charactersToRemove); System.out.println("Original String: " + originalString); System.out.println("Result String: " + resultString); 

    In this example, we remove the last 3 characters from the originalString, resulting in "Hello, Wo" in resultString.

  2. Using StringBuilder:

    You can use the StringBuilder class to efficiently remove the last characters from a String. Here's an example:

    String originalString = "Hello, World!"; int charactersToRemove = 3; // Number of characters to remove from the end StringBuilder stringBuilder = new StringBuilder(originalString); stringBuilder.delete(stringBuilder.length() - charactersToRemove, stringBuilder.length()); String resultString = stringBuilder.toString(); System.out.println("Original String: " + originalString); System.out.println("Result String: " + resultString); 

    This code creates a StringBuilder from the originalString, deletes the specified number of characters from the end, and then converts it back to a String using toString().

Both of these approaches will effectively remove the last characters from a String variable. Choose the one that best fits your specific use case and coding style.


More Tags

child-process android-adapter titlebar paste frameworks strtotime ms-access-2003 xcode control-panel mergesort

More Java Questions

More Dog Calculators

More General chemistry Calculators

More Biology Calculators

More Chemical reactions Calculators