string buffers
StringBuffer class
When learning the string class, the API says that the string buffers support variable strings, what is a string buffer? Next we'll look at the string buffers.
Lookup StringBuffer's Api,stringbuffer, also known as the variable character sequence , is a string-like buffer that can be changed by some method calls to the length and content of the sequence.
The original stringbuffer is a string buffer, that is, it is a container , the container can be loaded with a lot of strings. and the ability to perform various operations on the strings.
the StringBuffer method uses
Code Demo:
Creates a string buffer object. Used to store data.
StringBuffer sb = new StringBuffer ();
SB.Append("haha"); Add a String
SB.Insert(2, "it");//insert at specified location
sb.Delete(1, 4);//delete (front closed rear open)
SB.Replace(1, 4, "cast");//replace the content within the specified range (front-closed)
String str = sb.tostring ();
Note: After the Append, delete, insert, replace, and reverse method calls, the return value is the current object itself , so stringbuffer it can change the length and content of the character sequence .
method chaining calls to Objects
In our development, we encounter the case of returning an object after invoking a method. It then uses the returned object to continue calling the method. This time, we can put the code together now, like the Append method, the code is as follows:
Creates a string buffer object. Used to store data.
StringBuffer sb = new StringBuffer ();
Add data. After constantly adding data, to manipulate the last data of the buffer, it must be converted to a string.
String str = Sb.append (True). Append ("hehe"). ToString ();
StringBuffer Practice
Exercise: int[] arr = {34,12,89,68}; Convert elements in a int[] to string format [34,12,89,68]
Public Static String tostring_2 (int[] arr) {
StringBuffer sb = new stringbuffer ();
Sb.append ("[");
for (int i = 0; i < arr.length; i++) {
if (i!=arr.length-1) {
Sb.append (arr[i]+ ",");
}Else{
Sb.append (arr[i]+ "]");
}
}
return sb.tostring ();
}
No matter how much data, what type of data is not important, as long as the end becomes a string can use StringBuffer this container
StringBuilder class
The Lookup API Discovery also has a StringBuilder class, which is also a string buffer, what is the difference between StringBuilder and StringBuffer?
We read the API description of StringBuilder and found that it is also a variable sequence of characters. This class provides an API that is compatible with StringBuffer, but does not guarantee synchronization. This class is designed to be used as a simple replacement for stringbuffer, which is common when a string buffer is used by a single thread. If possible, it is recommended that this class be preferred because, in most implementations, it is faster than StringBuffer .
Java-StringBuffer and StringBuilder classes