~~ I thought it was prepared by the standard method of StringBuilder, but I couldn't find it no matter how I searched, so I made it myself. ~~ ↑ It was a misleading description ...
I wondered if there was a method specializing in erasing the specified number of characters from the end, but I couldn't find it when I searched for it, so I made it myself. is.
public class Demo {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("hoge");
//Delete one character from the end
sb.setLength(sb.length()-1);
//Execution result: hog
System.out.println(sb);
}
}
setlength
Sets the length of the string in the sequence.
length()
Returns the current length of the string. In the above example, 4 is returned.
All you have to do now is subtract the number of characters you want to delete from ``` length ()` ``.
Note that if you specify a string length less than 0, you will get an error `` `java.lang.StringIndexOutOfBoundsException```.
StringBuilder sb = new StringBuilder("hoge");
sb.setLength(sb.length()-5);
//Error: java.lang.StringIndexOutOfBoundsException: String index out of range: -1
setlength
Before you dostringbuilder
It may be better to check the length of.
//If n characters or more, delete n characters from the end
if (sb.length() >= n) {
sb.setLength(sb.length()-n);
}
delete(int start, int end)
Is the way to use.
I told you in the comments.
I first came up with it, but I thought it would be difficult to read because it was necessary to specify both the start position and the end position, so I rejected it.
length()
I thought I needed to write twice ...
In the first place, if you have length () in a variable, you only have to write it once! Readability isn't bad! I thought again. If there is the character delete, it is easy to understand that the character is deleted.
StringBuilder sb = new StringBuilder("hoge");
int n = 2; //Number of characters you want to delete from the end
int size = sb.length(); // length()In an int type variable
//Removed two-letter sentence from the end
sb.delete(size-n, size);
//Execution result: ho
System.out.println(sb);
The notes are the same as the sample source code ①, so they are omitted.
deletecharat(int index)
Is the way to use.
I also told you in the comments.
In this case, you can ** delete only one character from the end **. Please note that you cannot delete multiple characters from the end **.
However, I think it is (personally) more readable than the above two sample source codes. I was brilliantly showing the official documentation, but I couldn't notice it at all. So I will mention it in the commandments.
StringBuilder sb = new StringBuilder("hoge");
//Delete one character from the end
sb.deleteCharAt(sb.length()-1);
//Execution result: hog
System.out.println(sb);
Please let me know if there is a better implementation.
StringBuilder (Java Platform SE 8)
Recommended Posts