StringBuffer类提供针对字符的操作方法

StringBuffer类是Java中用于操作字符串的一个类,提供了许多针对字符的操作方法,例如:

  1. append():用于在字符串末尾添加字符或字符串。

  2. insert():用于在字符串的指定位置插入字符或字符串。

  3. delete():用于删除指定范围内的字符。

  4. reverse():用于反转字符串中的字符顺序。

  5. setCharAt():用于将字符串中指定位置的字符设置为指定字符。

public class Demo3 {
    public static void main(String[] args) {
        // 使用StringBuffer无参数的构造函数创建一个字符串缓冲类
        StringBuffer StB = new StringBuffer();
        System.out.println(StB);
        // 增加
        StB.append("abcjavaabc");
        System.out.println(StB);
        // 插入
        StB.insert(2,"小明");
        System.out.println(StB);
        // 删除(删除时,不包头也不包尾)
        StB.delete(2,4);
        System.out.println(StB);
        // 根据指定的索引值删除一个字符
        StB.deleteCharAt(3);
        System.out.println(StB);
        // 替换(根据指定的开始与结束索引值代替成指定的内容
        StB.replace(2,4,"钱多多");
        System.out.println(StB);
        // 翻转字符串的内容
        StB.reverse();
        System.out.println(StB);
        // 把指定索引值的字符替换指定的字符
        StB.setCharAt(3,'红');
        System.out.println(StB);
        // 根据指定的索引值截取字串
        String subString = StB.substring(2,4);
        System.out.println("字串内容:"+subString);
        // 查找指定字符第一次出现的位置
        int index = StB.indexOf("abc",3);
        System.out.println("索引值为:"+index);
        StB.append("javajava");
        System.out.println("查看字符数组的长度:"+StB.capacity());
        System.out.println("存储的字符个数:"+StB.length());
        System.out.println("索引指定的索引值查找字符:"+StB.charAt(2));
        System.out.println("字符串缓冲类的内容:"+StB);

    }
}

运行截图:

猜你喜欢

转载自blog.csdn.net/Sunny_Boy0518/article/details/134103826