Java 基础(StringBuffer, StringBuilder)

StringBuffer类

stringBuffer 类不同于 String,其对象必须使用构造器生成。有三个构造器:

  • stringBuffer(): 初始容量为16的字符串缓冲区
  • StringBuffer(int size): 构造指定容量的字符串缓冲区
  • StringBuffer(String str): 将内容初始化为指定字符串内容

String、 StringBuffer、StringBuilder 三者的异同

  • String: 不可变的字符序列;底层使用char[]存储
  • stringBuffer: 可变的字符序列;线程安全的,效率低; 底层使用char[]存储,创建了一个长度为16的数组。扩容的时候,若干添加的数据底层数组盛不下,那就需要扩容底层的数组,默认情况下,扩容为原来容量的2倍 +2,同时将原有数组中的元素复制到新的数组中。
  • StringBuilder: 可变的字符序列; jdk5.e新增的,线程不安全的,效率高; 底层使用char[]存储

开发中建议大家使用: StringBuffer(int capacity)或 StringBuilder(int capacity)

stringBuffer的常用方法:

stringBuffer append(xxx): 提供了很多的append()方法,用于进行字符串拼接
stringBuffer delete(int start,int end): 删除指定位置的内容
StringBuffer replace(int start, int end,String str): 把[start, end)位置替换为str
stringBuffer insert(int offset,xxx): 在指定位置插入 xxx
StringBuffer reverse(): 把当前字符序列逆转
public int indexof (String str): 查找字符串中指定字符或字串首次出现的位置,返回索引值。该方法区分大小写
public string substring(int start,int end): 返回一个从start开始到end索引结束的左闭右开区间的子字符串
public int Length(): 返回字符串的实际长度
public char charAt(int n): 方法返回此序列中指定索引处的char值
public void setcharAt(int n ,char ch): 该方法的作用是修改对象中索引值为index位置的字符为新的字符ch

代码

package com.klvchen.java;

import org.junit.Test;

public class StringBufferBuilderTest {

    @Test
    public void test2(){
        StringBuffer s1 = new StringBuffer("abc");
        s1.append(1);
        s1.append("1");
        System.out.println(s1);
        s1.delete(2,4);
        System.out.println(s1);
        s1.replace(2, 4, "hello");
        s1.insert(2, false);
        s1.reverse();
        String s2 = s1.substring(1, 3);
        System.out.println(s1);
        System.out.println(s1.length());
        System.out.println(s2);
    }
}
posted @ 2021-08-25 22:10  klvchen  阅读(52)  评论(0编辑  收藏  举报