Java Tour (17)--stringbuffer Overview, store, delete, get, modify, invert, store buffer data into an array, StringBuilder
After we finish the string, let's talk about his little brother.
I. StringBuffer overview
What does buffer mean about the object of StringBuffer? The meaning of the buffer, string once initialized can not be changed, and StringBuffer is possible, which is the difference, features:
- StringBuffer is a container
- Multiple data types can be manipulated in bytes
- Will eventually become a string through the ToString method
With this trait, let's take it a step at a moment.
PackageCom.lgl.hellojava;//public class class name Public class Hellojjava { Public Static void Main(string[] args) {/** * StringBuffer * *StringBuffer SB =NewStringBuffer (); StringBuffer append = Sb.append ( +); SOP (SB = = append); SOP (Sb.tostring ()); SOP (Append.tostring ()); }/** * Output * * Public Static void SOP(Object obj) {System.out.println (obj); } }
This is more common, we don't need to be so troublesome, we can simplify
sb.append("abc").append(36);sop(sb.toString());
We can directly output the string
This sequential method is called the method call chain
Because of the characteristics of stringbuffer, we can insert the data inside, I now want to insert a string after a, how to implement it?
sb.append("abc").append(36);sb.insert(1"lgl");sop(sb.toString());
That's right. Insert, his two parameters, one is subscript, one is data, so we insert successfully
Let's talk about it again. Delete
/** * 删除 */ publicstaticvoidmethod_delete() { new StringBuffer("abcdefg"); sop(sb.toString()); // 删除bc // sop(sb.delete(1, 3).toString()); // 删除d sop(sb.deleteCharAt(3)); // 清空缓冲区 sop("all:" + sb.delete(0, sb.length())); }
In fact, these are relatively simple
OK, in order we are now talking about getting, in fact, we have already talked about the string, there is not much to say. We say modify, modify is more classic, modify the data we write this way
/** * 修改 */ publicstaticvoidmethod_update() { new StringBuffer("abcdefg"); // 替换一部分 sop(sb.replace(14"java")); // 替换一个 1‘k‘); sop(sb.toString()); }
Results
OK, the modification succeeds, and the buffer is stored in the array
/** * Store data in the buffer in the array * / Public Static void Method_getchar() {StringBuffer SB =NewStringBuffer ("ABCDEFG");Char[] CHS =New Char[4];/** * Starting from 1, 4 ends, exists in CHS, starts from 1 * /Sb.getchars (1,4, CHS,1); for(inti =0; i < chs.length; i++) {SOP ("char["+ i +"] = "+ Chs[i] +";"); } }
Output of the results, hehe
Two. StringBuilder
It's only after JDK1.5.
- StringBuffer: Thread Synchronization
- StringBuilder: Thread not synchronizing
StringBuilder is not recommended in development
Let's take a look at his API description:
The use of the same, not much to say, this article is free to here
Interested in Dabigatran: 555974449
Java Tour (17)--stringbuffer Overview, store, delete, get, modify, invert, store buffer data into an array, StringBuilder