zoukankan      html  css  js  c++  java
  • java-StringBuffer类

    1、StringBuffer类概述
      1)我们如果对字符串进行拼接操作,每次拼接,都会构建一个新的String对象,既耗时,又浪费空间。而StringBuffer就可以解决这个问题
      2)线程安全的可变字符序列
      3)StringBuffer和String的区别
        · 前者长度和内容可变,后者不可变。
              · 如果使用前者做字符串的拼接,不会浪费太多的资源。
     
    2、构造方法
            · public StringBuffer() :无参构造方法
            · public StringBuffer(int capacity) :指定容量的字符串缓冲区对象
            · public StringBuffer(String str) :指定字符串内容的字符串缓冲区对象
         StringBuffer的方法:
        · public int capacity():返回当前容量,理论值
        · public int length():返回长度(字符数)  ,实际值
    复制代码
    public class StringBufferDemo01 {
        public static void main(String[] args) {
            // public StringBuffer():无参构造方法
            StringBuffer sb = new StringBuffer();
            System.out.println("sb:"+sb);
            System.out.println("sb.capacity:"+sb.capacity()); //16
            System.out.println("sb.length:"+sb.length()); //0
            System.out.println("--------------------------");
            // public StringBuffer(int capacity):指定容量的字符串缓冲区对象
            StringBuffer sb2 = new StringBuffer(50);
            System.out.println("sb2:"+sb2);
            System.out.println("sb2.capacity:"+sb2.capacity()); //50
            System.out.println("sb2.length:"+sb2.length()); //0
            System.out.println("--------------------------");
            // public StringBuffer(String str):指定字符串内容的字符串缓冲区对象
            StringBuffer sb3 = new StringBuffer("hello");
            System.out.println("sb3:"+sb3); //"hello"
            System.out.println("sb3.capacity:"+sb3.capacity()); //21
            System.out.println("sb3.length:"+sb3.length());//5
            System.out.println("--------------------------");
        }
    }
    复制代码

    注意返回值,可以查看源码,默认空间是16。

    复制代码
    /**
         * Constructs a string buffer with no characters in it and an
         * initial capacity of 16 characters.
         */
        public StringBuffer() {
            super(16);
        }
        /**
         * Constructs a string buffer with no characters in it and
         * the specified initial capacity.
         *
         * @param      capacity  the initial capacity.
         * @exception  NegativeArraySizeException  if the <code>capacity</code>
         *               argument is less than <code>0</code>.
         */
        public StringBuffer(int capacity) {
            super(capacity);
        }
        /**
         * Constructs a string buffer initialized to the contents of the
         * specified string. The initial capacity of the string buffer is
         * <code>16</code> plus the length of the string argument.
         *
         * @param   str   the initial contents of the buffer.
         * @exception NullPointerException if <code>str</code> is <code>null</code>
         */
        public StringBuffer(String str) {
            super(str.length() + 16);
            append(str);
        }
    复制代码
     
    3、StringBuffer类的成员方法
      1)添加功能
                · public StringBuffer append(String str):可以把任意类型数据添加到字符串缓冲区里面,并返回字符串缓冲区本身
                · public StringBuffer insert(int offset,String str):在指定位置把任意类型的数据插入到字符串缓冲区里面,并返回字符串缓冲区本身
    复制代码
    public class StringBufferDemo02 {
        public static void main(String[] args) {
            // 创建字符串缓冲区对象
            StringBuffer sb = new StringBuffer();
            //返回对象本身
            StringBuffer sb2 = sb.append("hello");
            System.out.println("sb:"+sb); //sb:hello
            System.out.println("sb2:"+sb2); //sb2:hello
            System.out.println(sb == sb2); //true
            //一步一步的添加数据
            StringBuffer sb3 = new StringBuffer();
            sb3.append("hello");
            sb3.append(true);
            sb3.append(12);
            sb3.append(34.56);
            System.out.println("sb3:"+sb3); //sb3:hellotrue1234.56
            //链式编程
            StringBuffer sb4 = new StringBuffer();
            sb4.append("hello").append(true).append(12).append(34.56);
            System.out.println("sb4:"+sb4); //sb4:hellotrue1234.56
            //StringBuffer insert(int offset,Stringstr):插入数据
            sb3.insert(5,"hello");
            System.out.println("sb3:"+sb3); //sb3:hellohellotrue1234.56
        }
    }
    复制代码
      2)删除功能
                · public StringBuffer deleteCharAt(int index):删除指定位置的字符,并返回本身
                · public StringBuffer delete(int start,int end):删除从指定位置开始指定位置结束的内容,并返回本身
    复制代码
    public class StringBufferDemo03 {
        public static void main(String[] args) {
            // 创建对象
            StringBuffer sb1 = new StringBuffer();
            // 创建对象
            sb1.append("hello").append("world").append("java");
            System.out.println("sb1:"+sb1); //sb1:helloworldjava
            // public StringBuffer deleteCharAt(int index):删除指定位置的字符,并返回本身
            // 需求:我要删除e这个字符
            sb1.deleteCharAt(1);
            // 需求:我要删除第一个l这个字符
            sb1.deleteCharAt(1);
            System.out.println("sb1:"+sb1);  //sb1:hloworldjava
            System.out.println("----------------");
            // public StringBuffer delete(int start,int end):删除从指定位置开始指定位置结束的内容,并返回本身
            StringBuffer sb2 = new StringBuffer("Hello World Java");
            System.out.println("sb2:"+sb2); //sb2:Hello World Java
            // 需求:我要删除World这个字符串
            sb2.delete(5,11);
            System.out.println("sb2:"+sb2); //sb2:Hello Java
            // 需求:我要删除所有的数据
            sb2.delete(0, sb2.length());
            System.out.println("sb2:"+sb2); //sb2:
        }
    }
    复制代码
      3)替换功能
                · public StringBuffer replace(int start,int end,String str):使用给定String中的字符替换词序列的子字符串中的字符
    复制代码
    public class StringBufferDemo04 {
        public static void main(String[] args) {
            // 创建字符串缓冲区对象
            StringBuffer sb = new StringBuffer();
            // 添加数据
            sb.append("hello");
            sb.append("world");
            sb.append("java");
            System.out.println("sb:" + sb); //sb:helloworldjava
            // public StringBuffer replace(int start,int end,String str):从start开始到end用str替换
            // 需求:我要把world这个数据替换为"节日快乐"
            sb.replace(5,10,"节日快乐");
            System.out.println("sb:"+sb); //sb:hello节日快乐java
        }
    }
    复制代码
      4)反转功能  
                · public StringBuffer reverse():将此字符序列用其反转形式取代,返回对象本身
    复制代码
    public class StringBufferDemo05 {
        public static void main(String[] args) {
            //创建字符串缓冲区对象
            StringBuffer sb = new StringBuffer();
            //添加数据
            sb.append("林青霞爱我");
            System.out.println("sb:"+sb); //sb:林青霞爱我
            //public StringBuffer reverse()
            sb.reverse();
            System.out.println("sb:"+sb); //sb:我爱霞青林
        }
    }
    复制代码
      5)截取功能
                · public String substring(int start):返回一个新的String,它包含此字符序列当前所包含的字符子序列
                · public String substring(int start,int end):返回一个新的String,它包含此序列当前所包含的字符子序列
            注意:截取功能和前面几个功能的不同
                · 返回值类型是String类型,本身没有发生改变
    复制代码
    public class StringBufferDemo06 {
        public static void main(String[] args) {
            //创建字符串缓冲区对象
            StringBuffer sb = new StringBuffer();
            sb.append("hello").append("world").append("java");
            System.out.println("sb:"+sb); //sb:helloworldjava
            //截取功能
            String s = sb.substring(5);
            System.out.println("s:"+s); //s:worldjava
            System.out.println("sb:"+sb); //sb:helloworldjava
            String ss = sb.substring(5,10);
            System.out.println("ss:"+ss); //ss:world
            System.out.println("sb:"+sb); //sb:helloworldjava
        }
    }
    复制代码

    4、练习题:String与StringBuffer的相互转换

    复制代码
    public class StringBufferDemo07 {
        public static void main(String[] args) {
            //String --> StringBuffer
            String s = "hello";
            // 注意:不能把字符串的值直接赋值给StringBuffer
            // StringBuffer sb = "hello";
            // StringBuffer sb = s;
            //方式一:通过构造方法
            StringBuffer sb = new StringBuffer(s);
            //方式二:通过append方法
            StringBuffer sb2 = new StringBuffer();
            sb2.append(s);
            System.out.println("sb:"+sb); //sb:hello
            System.out.println("sb2:"+sb2); //sb2:hello
            System.out.println("-------------------------");
            //StringBuffer --> String
             StringBuffer buffer = new StringBuffer("java");
            //方式一:通过构造方法
            String str = new String(buffer);
            //方式二:通过toString()方法
            String str2 = buffer.toString();
            System.out.println("str:"+str); //str:java
            System.out.println("str2:"+str2); //str2:java
        }
    }
    复制代码

    5、练习题:把数组拼接成一个字符串

    复制代码
    public class StringBufferDemo08 {
        public static void main(String[] args) {
            //定义一个数组
            int[] arr = {44,33,55,11,22};
            //定义功能
            //方式一:用String做拼接的方式
            String result1 = arrayToString1(arr);
            System.out.println("result1:"+result1); //result1:[44,33,55,11,22]
            //方式二:用StringBuffer做拼接的方式
            String result2 = arrayToString2(arr);
            System.out.println("result2:"+result2); //result2:[44,33,55,11,22]
        }
        public static String arrayToString1(int[] arr){
            String s = "";
            s += "[";
            for(int x = 0; x < arr.length; x++){
                if (x == arr.length - 1){
                    s += arr[x];
                }else{
                    s += arr[x];
                    s += ',';
                }
            }
            s += ']';
            return s;
        }
        public static String arrayToString2(int[] arr){
            StringBuffer sb = new StringBuffer();
            sb.append("[");
            for(int x = 0; x < arr.length; x++){
                if (x == arr.length-1){
                    sb.append(arr[x]);
                }else{
                    sb.append(arr[x]).append(",");
                }
            }
            sb.append("]");
            return sb.toString();
        }
    }
    复制代码

    6、练习题:把字符串反转

    复制代码
    public class StringBufferDemo09 {
        public static void main(String[] args) {
            String s = "I love Java";
            String result1 = myReverse1(s);
            System.out.println("result1:"+result1); //result1:avaJ evol I
            String result2 = myReverse2(s);
            System.out.println("result2:"+result2); //result2:avaJ evol I
        }
        public static String myReverse1(String s){
            String result = "";
            char[] ch = s.toCharArray();
            for(int x = s.length()-1; x >= 0; x--){
                result += ch[x];
            }
            return result;
        }
        public static String myReverse2(String s){
            return new StringBuffer(s).reverse().toString();
        }
    }
    复制代码

    7、判断一个字符串是否是对称的。

    复制代码
    public class StringBufferDemo10 {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.println("请输入一个字符串:");
            String str = sc.nextLine();  //abcba
            boolean result1 = isSymmertrical1(str);
            System.out.println("result1:"+result1); //result1:true
            boolean result2 = isSymmertrical2(str); //result2:true
            System.out.println("result2:"+result2);
        }
        public static boolean isSymmertrical1(String s){
            boolean flag = true;
            char ch[] = s.toCharArray();
            for(int start = 0, end = ch.length-1; start <= end;start++,end--){
                if (ch[start] != ch[end]){
                    flag = false;
                    break;
                }
            }
            return flag;
        }
        public static boolean isSymmertrical2(String s){
            return new StringBuffer(s).reverse().toString().equals(s);
        }
    }
    复制代码
     
    8、了解一下StringBuilder类
            一个可变的字符序列。此类提供一个与 StringBuffer 兼容的 API,但不保证同步。该类被设计用作 StringBuffer 的一个简易替换,用在字符串缓冲区被单个线程使用的时候(这种情况很普遍)。如果可能,建议优先采用该类,因为在大多数实现中,它比 StringBuffer 要快。
            只要将StringBuffer的功能替换到StringBuilder就可以了。
        
    9、String,StringBuffer,StringBuilder的区别
      1)String是内容不可变的,而StringBuffer,StringBuilder都是内容可变的。
      2)StringBuffer是同步的,数据安全,效率低;StringBuilder是不同步的,数据不安全,效率高
     
    10、StringBuffer和数组的区别?
                A:二者都可以看出是一个容器,装其他的数据。
                B:但是呢,StringBuffer的数据最终是一个字符串数据。
                C:而数组可以放置多种数据,但必须是同一种数据类型的。

    11、形式参数问题
            A:String作为参数传递
            B:StringBuffer作为参数传递
            形式参数:
          基本类型:形式参数的改变不影响实际参数
          引用类型:形式参数的改变直接影响实际参数
            注意:
        String作为参数传递,效果和基本类型作为参数传递是一样的。
    复制代码
    public class StringBufferDemo11 {
        public static void main(String[] args) {
            String s1 = "hello";
            String s2 = "world";
            System.out.println(s1 + "---" + s2);//hello---world
            change(s1, s2);
            System.out.println(s1 + "---" + s2);//hello---world
            StringBuffer sb1 = new StringBuffer("hello");
            StringBuffer sb2 = new StringBuffer("world");
            System.out.println(sb1 + "---" + sb2);//hello---world
            change(sb1, sb2);
            System.out.println(sb1 + "---" + sb2);//hello---worldworld
        }
        //Stringz作为形参传递不会改变实参
        public static void change(String s1, String s2) {
            s1 = s2;
            s2 = s1 + s2;
        }
        //StringBuffer作为形参,如果直接赋值则不会影响实参,但是如果是使用方法改变形参则会影响实参
        public static void change(StringBuffer sb1, StringBuffer sb2) {
            sb1 = sb2;
            sb2.append(sb1);
        }
    }
    复制代码
     
  • 相关阅读:
    docker搭建mongodb
    mongodb的搭建
    Mysql错误:Ignoring query to other database解决方法
    BZOJ4567:[SCOI2016]背单词——题解
    BZOJ4570:[SCOI2016]妖怪——题解
    BZOJ4753:[JSOI2016]最佳团体——题解
    BZOJ1853:[SCOI2010]幸运数字 & BZOJ2393:Cirno的完美算数教室——题解
    LOJ6388:[THUPC2018]赛艇——题解
    BZOJ5217:[Lydsy2017省队十连测]航海舰队——题解
    BZOJ4259:残缺的字符串——题解
  • 原文地址:https://www.cnblogs.com/wuqiance/p/11605018.html
Copyright © 2011-2022 走看看