[Java] Delete the specified number of characters from the end of StringBuilder

Introduction

~~ 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.

Operation check environment

Sample source code ①

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);
    }
}

setlengthSets 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

setlengthBefore you dostringbuilderIt 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);
}

Sample source code ②

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.

Sample source code ③

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);

At the end

Please let me know if there is a better implementation.

References

StringBuilder (Java Platform SE 8)

Recommended Posts

[Java] Delete the specified number of characters from the end of StringBuilder
[Java] Check the number of occurrences of characters
[Java] Delete the elements of List
In Java, I want to trim multiple specified characters from only the beginning and end.
How to write Scala from the perspective of Java
Java language from the perspective of Kotlin and C #
Set the maximum number of characters in UITextField in RxSwift
A program that counts the number of words in a List
Aggregate the number of people every 10 years from List <Person>
[Java] Delete the specified number of characters from the end of StringBuilder
Get to the abbreviations from 5 examples of iterating Java lists
Java end of month plusMonths
Command to check the number and status of Java threads
Count the number of digits after the decimal point in Java
Aggregate the number of people every 10 years from List <Person>
Method to add the number of years and get the end of the month
From fledgling Java (3 years) to Node.js (4 years). And the impression of returning to Java
I tried to summarize the methods of Java String and StringBuilder
[Swift] The color of the Navigation Bar is different (lighter) from the specified color.
Let's summarize the Java 8 grammar from the perspective of an iOS engineer
The road from JavaScript to Java
The origin of Java lambda expressions
Dynamically increase the number of elements in a Java 2D array (multidimensional array)
[Java Servlet] The road of Senri is also the fifth step from the first step
The story of acquiring Java Silver in two months from completely inexperienced.
From Java9, the constructor of the class corresponding to primitive types is deprecated.
I translated the grammar of R and Java [Updated from time to time]
[Java] Get MimeType from the contents of the file with Apathce Tika [Kotlin]
Get the result of POST in Java
Check the contents of the Java certificate store
Examine the memory usage of Java elements
[Java] Get the day of the specific day of the week
Memo: [Java] Check the contents of the directory
Kick ShellScript on the server from Java
Hit the Salesforce REST API from Java
Compare the elements of an array (Java)
How to determine the number of parallels
The story of RxJava suffering from NoSuchElementException
[day: 5] I summarized the basics of Java
Ruby from the perspective of other languages
What are the updated features of java 13
Easily measure the size of Java Objects
Looking back on the basics of Java
Deletes after the specified character from the character string
Output of the book "Introduction to Java"
About the number of threads of Completable Future
The story of writing Java in Emacs
Find the difference from a multiple of 10
[Java] [Spring] Test the behavior of the logger
[Promotion of Ruby comprehension (1)] When switching from Java to Ruby, first understand the difference.
Increment with the third argument of iterate method of Stream class added from Java9
[Java] Calculate the day of the week from the date (Calendar class is not used)