0
点赞
收藏
分享

微信扫一扫

StringBuffer常用方法操作

zhoulujun 2022-01-24 阅读 60

StringBuffer类的使用(字符串缓冲区)
String类与StringBuffer类的不同:String类表示的字符串是产量,一旦创建其内容与长度将无法修改,StringBuffer类表示字符容器,其内容与长度可以随时修改
StringBuffer主要的有增加(add),删除(remove),修改(alter)

public class StringBufferTest {
    public static void main(String[] args) {
        System.out.println("1.添加-----------------");
        add();
        System.out.println("2.删除-----------------");
        remove();
        System.out.println("3.修改-----------------");
        alter();
    }

    public static void add(){
        StringBuffer sb = new StringBuffer(); //定义一个字符串缓冲区
        sb.append("abcdefg");//在末尾添加字符串
        System.out.println("append添加结果:"+sb);
        sb.insert(3,"KK"); //在指定位置插入字符串
        System.out.println("insert插入的结果:"+sb);
    }

    public static void remove(){
        StringBuffer sb = new StringBuffer("abcdefg");
        sb.delete(1,5); //在指定范围内删除
        System.out.println("delete删除指定范围的结果:"+sb);
        sb.deleteCharAt(2); //删除指定位置的元素
        System.out.println("deleteCharAt删除指定位置的元素结果:"+sb);
        sb.delete(0,sb.length()); // 清空缓冲区
        System.out.println("清空缓冲区的结果:"+sb);
    }

    public static void alter(){
        StringBuffer sb = new StringBuffer("abcdefg");
        sb.setCharAt(1,'P');
        System.out.println("修改指定位置字符结果:"+sb);
        sb.replace(0,4,"KKKK"); //结束位置实际为end-1
        System.out.println("替换指定位置字符或者字符串结果:"+sb);
        System.out.println("反转字符串结果:"+sb.reverse());
    }
}

运行结果如下所示:

1.添加-----------------
append添加结果:abcdefg
insert插入的结果:abcKKdefg
2.删除-----------------
delete删除指定范围的结果:afg
deleteCharAt删除指定位置的元素结果:af
清空缓冲区的结果:
3.修改-----------------
修改指定位置字符结果:aPcdefg
替换指定位置字符或者字符串结果:KKKKefg
反转字符串结果:gfeKKKK

Process finished with exit code 0
举报

相关推荐

0 条评论