Question:
What ways to remove a certain number 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 the string "123456789"
as an example, and a variable with the number of characters to remove
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());
-
Making use of the StringBuilder class to assign the size of the output string in this case the value obtained above
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 and then passing saidArray
to theString
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 by the number of characters to Remove)
System.out.println(string.replaceFirst("[\\s\\S]{0,2}$", ""));
The String data type cannot be modified after being created. (Immutable)