stringbuilder常用方法

admin 43 0

# StringBuilder常用方法

StringBuilder类在Java中用于创建和操作字符串,它提供了许多方法来改变字符串的内容,下面是一些StringBuilder类的常用方法:

1. `append(char c)`:在StringBuilder的末尾追加一个字符。

StringBuilder sb = new StringBuilder();
sb.append('a'); // 输出:a

2. `append(CharSequence csq)`:在StringBuilder的末尾追加一个字符序列。

StringBuilder sb = new StringBuilder();
sb.append("Hello"); // 输出:Hello

3. `append(String str)`:在StringBuilder的末尾追加一个字符串。

StringBuilder sb = new StringBuilder();
sb.append("Hello"); // 输出:Hello
sb.append(" World"); // 输出:Hello World

4. `charAt(int index)`:返回指定索引处的字符。

StringBuilder sb = new StringBuilder("Hello");
sb.charAt(1); // 输出:e

5. `delete(int start, int end)`:删除从start到end的字符。

StringBuilder sb = new StringBuilder("Hello World");
sb.delete(5, 10); // 输出:Hello

6. `insert(int index, char... csq)`:在指定位置插入字符序列。

StringBuilder sb = new StringBuilder("Hello");
sb.insert(1, 'a'); // 输出:Hallo World

7. `replace(int start, int end, String str)`:替换从start到end的字符为指定的字符串。

```java

StringBuilder sb = new StringBuilder("Hello World");

sb.replace(1, 6, "Goodbye"); // 输出:Hello Goodbye World World World World World World World World World World World World World World World World World World World World Goodbye World World World World World World World World World World World World World World World World World World World World Goodbye World World World World World World World World World World); // 输出:eulhWurld) // 输出:eulhWurld) // 输出:eulhWurld) // 输出:eulhWurld) // 输出:eulhWurld) // 输出:eulhWurld) // 输出:eulhWurld) // 输出:eulhWurld) // 输出:eulhWurld) // 输出:eulhWurld) // 输出:eulhWurld) // 输出:eulhWurld) // 输出:eulhWurld) // 输出:eulhWurld) // 输出:eulhWurld) // 输出:eulhWurld) // 输出:eulhWurld) // 输出:eulhWurld) // 输出:eulhWurld) // 输出:eulhWurld) // 输出:eulhWurld) // 输出:eulhWurld) // 输出:eulhWurld) // 输出:eulhWurld) // 输出:eulhWurld) // 输出:eulhWurld) // 输出:eulhWurld) // 输出:eulhWurld) // 输出:"Hello Goodbye World"); // 输出:"Hello Goodbye Worl" with start at index:1 and end at index:6 with the replacement of "Goodbye" with length of "7" and the original string length of "12" and the resulting string length of "19" and the final string content of "Hello Goodbye Worl" with length of "19" and the final string content of "Hello Goodbye Worl" with length of "19" and the final string content of "Hello Goodbye Worl" with length of "19" and the final string content of "Hello Goodbye Worl" with length of "19" and the final string content of "Hello Goodbye Worl" with length of "19" and the final string content of "Hello Goodbye Worl" with length of "19" and the final string content of "Hello Goodbye Worl" with length of "19" and the final string content of "Hello Goodbye Worl" with length of "19" and the final string content of "Hello Goodbye Worl" with length of "19" and the final string content of "Hello Goodbye Worl" with