StringBuffer类的操作方法

String:     字符串常量

StringBuffer:  字符串变量(线程安全)

StringBuilder:   字符串变量(线程不安全)

执行效率:   大部分情况下 Stringbuilder>StringBuffer>String

StringBuffer类的增删改查:

1、查找方法:

    public static void main(String[] args) {
        StringBuffer sb=new StringBuffer("this is StringBuffer");
        //查找子字符串首次出现的下标,不存在返回-1
        System.out.println(sb.indexOf("Str"));
        System.out.println(sb.indexOf("str"));
        //指定开始下标,返回首次出现下标,不存在返回-1;
        System.out.println(sb.indexOf("Str",3));
        System.out.println(sb.indexOf("Str",9));
        //查找子字符串最后出现的下标,不存在返回-1;
        System.out.println(sb.lastIndexOf("is"));
        //指定子字符串结束下标,不存在返回-1;
        System.out.println(sb.lastIndexOf("is",4));
     //查找指定下标的字符  
     System.out.println(sb.charAt(1)); }

2、增:

1     public static void main(String[] args) {
2         StringBuffer sb=new StringBuffer("this is StringBuffer");
3         //在字符串尾部追加字符串
4         System.out.println(sb.append("\t wey"));
5         //在指定位置插入字符串
6         System.out.println(sb.insert(4, "wey"));
7     }

3、改:

    public static void main(String[] args) {
        StringBuffer sb=new StringBuffer("this is StringBuffer");
        //指定开始,结束下标区间字符替换成指定字符串;
        System.out.println(sb.replace(0, 4, "who"));
    }

4、删:

    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("this is StringBuffer");
        // 删除指定开始、结束下标区间的字符
        System.out.println(sb.delete(0, 4));
        // 删除指定下标的字符
        System.out.println(sb.deleteCharAt(1));
    }

5、截取字符串:

    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("this is StringBuffer");
        // 截取指定区间的字符串
        System.out.println(sb.substring(0, 4));
        // 开始下标截取字符串,结束下标默认字符串结尾
        System.out.println(sb.substring(2));
    }

6、字符串反转:

扫描二维码关注公众号,回复: 1996031 查看本文章
public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("this is StringBuffer");
        // 字符串反转
        System.out.println(sb.reverse());
    }

猜你喜欢

转载自www.cnblogs.com/corexy/p/9284477.html