StringBuilder
时间: 2023-11-07 18:56:43 浏览: 66
StringBuilder is a class in Java that is used to create and manipulate strings. It is an alternative to the String class that provides more efficient and flexible ways to create and modify string objects.
The StringBuilder class provides methods for appending, inserting, deleting, and replacing characters in a string. It also allows you to set the length of the string and to convert the string to a character array.
One of the main benefits of using StringBuilder is that it is mutable, meaning that you can change the contents of the string without creating a new object. This can be more efficient than creating a new String object every time you need to modify the string.
Here's an example of using StringBuilder to create a new string:
```
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("World");
String result = sb.toString(); // "Hello World"
```
In this example, we create a new StringBuilder object and use the `append()` method to add the words "Hello" and "World" to it. We then convert the StringBuilder object to a String using the `toString()` method and assign it to the `result` variable. The final result is the string "Hello World".
阅读全文