- import java.util.Arrays;
- public class StringBuilderDemo {
- public static void main(String[] args) {
- //创建StringBuilder对象
- StringBuilder stringBuilder = new StringBuilder();
-
- //将指定数据添加到已有数据的末尾
- stringBuilder.append("This ");
- stringBuilder.append(" a StringBuilder type.");
-
- //将指定数据添加到指定的位置
- stringBuilder.insert(5, "is");
-
- //将数据转换为String
- System.out.println(stringBuilder.toString());
-
- //将[start, end)数据删除。删除"this"
- stringBuilder.delete(0, 4);
-
- //删除指定索引的字符
- stringBuilder.deleteCharAt(0);
- System.out.println(stringBuilder.toString());
-
- //获取指定索引0的字符
- System.out.println(stringBuilder.charAt(0));
-
- //获取指定字符串"Stri"的第一个索引
- System.out.println(stringBuilder.indexOf("Stri"));
-
- //获取指定字符串"e"的最后一个索引
- System.out.println(stringBuilder.lastIndexOf("e"));
-
- //返回指定区间的字符串
- System.out.println(stringBuilder.substring(0, 3));
-
- //将指定区间的数据替换
- System.out.println(stringBuilder.replace(0, 3, "KKKKKKKKKKK"));
-
- //设定指定索引的字符
- stringBuilder.setCharAt(0, 'J');
- System.out.println(stringBuilder.toString());
-
- //反转
- System.out.println("reversed: " + stringBuilder.reverse().toString());
- System.out.println("original: " + stringBuilder.toString());
-
- //将缓冲区指定区间的数据填充到数组中
- char[] chars = new char[100];
- for (int i = 0; i < chars.length; i++) {
- chars[i] = ' ';
- }
- stringBuilder.getChars(0, stringBuilder.length() - 1, chars, 2);
- System.out.println(chars);
- }
- }
复制代码
|
|