Clearing a stringbuilder java

Java StringBuilder delete() Method

The Java StringBuilder delete() method is used to remove the characters in a substring of a sequence. The substring is the smaller part of the given string.

The substring begins at the specified startIndex and extends to the character at index endIndex — 1 or, the endIndex of the sequence if no such character exists. If the startIndex is equal to the endIndex, no changes are made.

The delete() method accepts two parameters as an integer that holds the value of startIndex and endIndex. It throws an exception if the startIndex value is negative, the endIndex value is greater than the sequence length, and the startIndex is greater than the end index.

Syntax

Following is the syntax of the Java StringBuilder delete() method −

public StringBuilder delete(int start, int end)

Parameters

  • start − This is the beginning index, inclusive.
  • end − This is the ending index, exclusive.

Return Value

This method returns the substring of this sequnece.

Example

If the startIndex value is greater than 0 and the endIndex value is less than the sequence length, it returns the substring of this sequence.

In the following program, first, we are instantiating the StringBuilder Class with the value “Welcome to Tutorials Point”. Using the delete() method, we are trying to delete the string at a given range (startIndex = 5 and endIndex = 10.).

package com.tutorialspoint.StringBuilder; import java.lang.*; public class StringBuilderDemo < public static void main(String[] args) < //create s StringBuilder StringBuilder sb = new StringBuilder("Welcome to Tutorials Point"); System.out.println("Before deletion the string is: " + sb); //initialize the startInde and endIndex values int startIndex = 11; int endIndex = 21; System.out.println("The startIndex and endIndex values are: " + startIndex + " and " + endIndex); //using the delete() method StringBuilder new_str = sb.delete(startIndex, endIndex); System.out.println("After deletion the remaing string is: " + new_str); >>

Output

On executing the above program, it will produce the following result −

Before deletion the string is: Welcome to Tutorials Point The startIndex and endIndex values are: 11 and 21 After deletion the remaing string is: Welcome to Point

Example

If the startIndex value is greater than the endIndex value, this method throws a StringIndexOutOfBoundsException.

In the following example, we are creating an object of the StringBuilder with the value “JavaProgramming”, Using the delete() method, we are trying to delete the string at the given range ( where startIndex > endIndex).

package com.tutorialspoint.StringBuilder; public class Demo < public static void main(String[] args) < try < //create an object of the StringBuilder StringBuilder sb = new StringBuilder("TutorialsPoint"); System.out.println("Before deletion the string is: " + sb); //initialize the startIndex and endIndex values int startIndex = 10;// greater than the endIndex value int endIndex = 5; System.out.println("The startIndex and endIndex values are: " + startIndex + " and " + endIndex); //using the delete() method System.out.println("After deletion rhe remaing string is: " + sb.delete(startIndex, endIndex)); >catch(IndexOutOfBoundsException e) < e.printStackTrace(); System.out.println("Exception: " + e); >> >

Output

Following is the output of the above program −

Before deletion the string is: TutorialsPoint The startIndex and endIndex values are: 10 and 5 java.lang.StringIndexOutOfBoundsException: start 10, end 5, length 14 at java.base/java.lang.AbstractStringBuilder.checkRangeSIOOBE(AbstractStringBuilder.java:1810) at java.base/java.lang.AbstractStringBuilder.delete(AbstractStringBuilder.java:917) at java.base/java.lang.StringBuilder.delete(StringBuilder.java:289) at com.tutorialspoint.StringBuilder.Demo.main(Demo.java:13) Exception: java.lang.StringIndexOutOfBoundsException: start 10, end 5, length 14

Example

If the startIndex contains a negative value, the delete() method throws an IndexOutOfBoundsException.

Читайте также:  Два символа после запятой php

In this example, we create a StringBuilder with the value“TutorialsPoint”. We are trying to delete a string at the given range(where the startIndex holds the negative value -2.) using the delete() method.

package com.tutorialspoint.StringBuilder; import java.lang.*; public class Delete < public static void main(String[] args) < try < //create an object of the StringBuilder StringBuilder sb = new StringBuilder("TutorialsPoint"); System.out.println("Before deletion the string is: " + sb); //initialize the startIndex and endIndex values int startIndex = -2;// holds negative value int endIndex = 5; System.out.println("The startIndex and endIndex values are: " + startIndex + " and " + endIndex); //using the delete() method System.out.println("After deletion rhe remaing string is: " + sb.delete(startIndex, endIndex)); >catch(IndexOutOfBoundsException e) < e.printStackTrace(); System.out.println("Exception: " + e); >> >

Output

The above program, produces the following results −

Before deletion the string is: TutorialsPoint The startIndex and endIndex values are: -2 and 5 java.lang.StringIndexOutOfBoundsException: start -2, end 5, length 14 at java.base/java.lang.AbstractStringBuilder.checkRangeSIOOBE(AbstractStringBuilder.java:1810) at java.base/java.lang.AbstractStringBuilder.delete(AbstractStringBuilder.java:917) at java.base/java.lang.StringBuilder.delete(StringBuilder.java:289) at com.tutorialspoint.StringBuilder.Delete.main(Delete.java:13) Exception: java.lang.StringIndexOutOfBoundsException: start -2, end 5, length 14

Источник

Clearing a StringBuilder or StringBuffer

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

Читайте также:  Серверы css my server

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We’re looking for a new Java technical editor to help review new articles for the site.

1. Overview

In this tutorial, we’ll present a couple of methods to clear a StringBuilder or StringBuffer, then elaborate on them.

2. Clearing a StringBuilder

2.1. Use the setLength Method

The method setLength updates the inner length of the StringBuilder. All entries after the length are then ignored when manipulating the StringBuilder. Thus, calling it with 0 clears its content:

@Test void whenSetLengthToZero_ThenStringBuilderIsCleared()

Let’s note that after we call the setLength method, the capacity of the StringBuilder remains the same.

2.2. Use the delete Method

The delete method uses System.arraycopy in the background. All indexes before the start index or after the end index are copied to the same StringBuilder.

Thus, if we call delete with a start index of 0 and an end index equal to the length of the StringBuilder, we’ll copy:

  • The indexes before 0: there are none.
  • The indexes after stringBuilder.length(): there are none.

As a result, all the content of the StringBuilder is removed:

@Test void whenDeleteAll_ThenStringBuilderIsCleared()

As with the setLength method, the object capacity remains the same after the deletion of its content. Let’s also underline that no new object creation was involved during this process.

Читайте также:  Php включить вывод ошибок php ini

3. Clearing a StringBuffer

All the methods that work for StringBuilder work in the same way with StringBuffer. Furthermore, all the remarks on the capacity of the objects remain valid.
Let’s showcase an example with the setLength method:

@Test void whenSetLengthToZero_ThenStringBufferIsCleared()

It is also possible to use the delete method:

@Test void whenDeleteAll_ThenStringBufferIsCleared()

4. Performance

Let’s do a quick performance comparison with JMH. Let’s compare each of the three methods for our StringBuilder:

@State(Scope.Benchmark) public static class MyState < final String HELLO = "Hello World"; final StringBuilder sb = new StringBuilder().append(HELLO); >@Benchmark public void evaluateSetLength(Blackhole blackhole, MyState state) < state.sb.setLength(0); blackhole.consume(state.sb.toString()); >@Benchmark public void evaluateDelete(Blackhole blackhole, MyState state)

We’ve measured the number of operations by second. This benchmark leads to the following result:

Benchmark Mode Cnt Score Error Units evaluateDelete thrpt 25 67943684.417 ± 18116791.770 ops/s evaluateSetLength thrpt 25 37310891.158 ± 994382.978 ops/s

As we can see, delete seems to be the less time-consuming method of the two by almost a factor of 2.

5. Conclusion

In this article, we’ve detailed three methods to clear a StringBuilder or a StringBuffer.

As always, the code is available over on GitHub.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

Java: очищаемм содержимое StringBuilder/StringBuffer

Для сложения большого количества строк гораздо эффективнее использовать объект StringBuilder (в многопоточной среде StringBuffer ). Но иногда возникает необходимость в очистке содержиммого StringBuilder -а. К сожалению данный класс не имеет метода, который бы очищал его содержимое. Но выход из ситуации есть: можно воспользоваться методом delete(int start, int end) класса StringBuilder , который удаляет строчки начиная с позиции start до позиции end .

В качестве начальной позиции необходимо указать 0, в в качестве конечной позиции — длинну содержимого StringBuilder-а. Выглядеть это все будет приерно так:

public class Test  public static void main (String[] args)  StringBuffer sb = new StringBuffer(); sb.append("This is StringBuilder "); sb.append("example"); System.out.println("StringBuilder content before cleaning: \n" + sb.toString()); //removing StringBuilder content sb.delete(0, sb.length()); sb.append("This is new StringBuilder content"); System.out.println("\n" + sb.toString()); > > 
StringBuilder content before cleaning: This is StringBuilder exampleThis is new StringBuilder content 

Для StringBuffer-а принцип такой же.

Источник

Оцените статью