How to remove last n characters from a string in Java? Java

Question:

What ways to remove a certain amount of characters from a string, for example cadena = "123456789" , I would like to remove last 2 characters from the string. the output would be "1234567" .

What ways are there to do this? that works for any number of characters to remove ( last )

Answer:

Taking as an example the string "123456789" , and a variable with the number of characters to delete

     String  cadena= "123456789";
     int cantidad= 2; /* Total de elementos a Eliminar*/  
      /* Total de elementos a Mostrar*/      
     int m = Math.max(0, cadena.length() - cantidad); 
  • Making use of the Substring (int start, int end) method, similar to SubSequence (int start, int end)

     System.out.println(cadena.substring(0, cadena.length()-cantidad)); System.out.println(cadena.subSequence(0, m).toString());
  • Using the StringBuilder class to assign the size of the output string in this case the value obtained previously m

     StringBuilder sb = new StringBuilder(cadena); sb.setLength(m); System.out.println(sb.toString());
  • Converting the string into an Array of Characters using the toCharArray () method to then pass said Array to the String Constructor new String (char [] chars, int a, int b)

     char[] cs = cadena.toCharArray(); System.out.println(new String(cs, 0, m));
  • Regular Expression (modify the 2 for the number of characters to Delete)

     System.out.println(string.replaceFirst("[\\s\\S]{0,2}$", ""));

The String data type cannot be modified after it is created. (Immutable)

Scroll to Top