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 )
Taking as an example the string
"123456789"
, and a variable with the number of characters to removeMaking use of the Substring(int start, int end) method , similar to SubSequence(int start, int end)
Making use of the StringBuilder class to assign the size of the output string in this case the value obtained previously
m
Converting the string to a Char
Array
using the toCharArray() method and then passing thatArray
to the Constructor of theString
new String(char[] chars,int a ,int b)Regular Expression (modify the 2 by the number of characters to Remove)
You can delete like this:
It is already eliminated you just have to play or vary the amount of characters you want to eliminate.
It is worth clarifying that Strings in java are immutable .
[substring(int)][1]
You can make use of the and method[length()][1]
,The simplest way
substring
is using the class methodjava.lang.String
. On the other hand, if you plan to reuse this code snippet with other strings and lengths, I recommend placing it in a method. That is (for example):❐ Code
❐ Exit