Summary of usage examples of Java StringBuffer and StringBuilder classes

  • 2021-07-09 08:08:02
  • OfStack

This article summarizes the usage of Java, StringBuffer and StringBuilder classes with examples. Share it for your reference, as follows:

The Construction Method of StringBuffer Class


package cn.itcast_01;
/*
 *  Thread safety ( Multithreaded explanation )
 *  Safety  --  Synchronization  --  The data is secure 
 *  Unsafe  --  Asynchronous  --  High efficiency 1 Some 
 *  Safety and efficiency are the problems that always bother us. 
 *  Security: Hospital websites, bank websites 
 *  Efficiency: News websites, forums and the like 
 * 
 * StringBuffer:
 *      A thread-safe mutable string. 
 * 
 * StringBuffer And String Difference between ?
 *  The length and content of the former are variable, while the latter is immutable. 
 *  If you use the former to splice strings, you won't waste too much resources. 
 * 
 * StringBuffer The construction method of: 
 *    public StringBuffer(): Parametric construction method 
 *    public StringBuffer(int capacity): String buffer object of specified size 
 *    public StringBuffer(String str): A string buffer object that specifies the contents of a string 
 *
 * StringBuffer Method of: 
 *    public int capacity() Returns the current capacity.    Theoretical value 
 *    public int length(): Returns the length (number of characters).   Actual value 
 */
public class StringBufferDemo {
  public static void main(String[] args) {
    // public StringBuffer(): Parametric construction method 
    StringBuffer sb = new StringBuffer();
    System.out.println("sb:" + sb);
    System.out.println("sb.capacity():" + sb.capacity());
    System.out.println("sb.length():" + sb.length());
    System.out.println("--------------------------");
    // public StringBuffer(int capacity): String buffer object of specified size 
    StringBuffer sb2 = new StringBuffer(50);
    System.out.println("sb2:" + sb2);
    System.out.println("sb2.capacity():" + sb2.capacity());
    System.out.println("sb2.length():" + sb2.length());
    System.out.println("--------------------------");
    // public StringBuffer(String str): A string buffer object that specifies the contents of a string 
    StringBuffer sb3 = new StringBuffer("hello");
    System.out.println("sb3:" + sb3);
    System.out.println("sb3.capacity():" + sb3.capacity());//16+5
    System.out.println("sb3.length():" + sb3.length());
  }
}

Additional features of StringBuffer:


package cn.itcast_02;
/*
 * StringBuffer Add functionality to: 
 * public StringBuffer append(String str): You can add any type of data to the string buffer , And returns the string buffer itself 
 * 
 * public StringBuffer insert(int offset,String str): Inserts any type of data into the string buffer at the specified position , And returns the string buffer itself 
 */
public class StringBufferDemo {
  public static void main(String[] args) {
    //  To create a string buffer object 
    StringBuffer sb = new StringBuffer();
//     public StringBuffer append(String str)
     StringBuffer sb2 = sb.append("hello");
     System.out.println("sb:" + sb);
     System.out.println("sb2:" + sb2);
     System.out.println(sb == sb2); // true
    // 1 Step 1 Add data to step 
    // sb.append("hello");
    // sb.append(true);
    // sb.append(12);
    // sb.append(34.56);
    //  Chain programming 
    sb.append("hello").append(true).append(12).append(34.56);
    System.out.println("sb:" + sb);
    // public StringBuffer insert(int offset,String
    // str): Inserts any type of data into the string buffer at the specified position , And returns the string buffer itself 
    sb.insert(5, "world");
    System.out.println("sb:" + sb);
  }
}

Delete function of StringBuffer


package cn.itcast_03;
/*
 * StringBuffer Delete function of 
 * public StringBuffer deleteCharAt(int index): Deletes the character at the specified position and returns itself 
 * public StringBuffer delete(int start,int end): Deletes content that starts at the specified location and ends at the specified location, and returns itself 
 */
public class StringBufferDemo {
  public static void main(String[] args) {
    //  Create an object 
    StringBuffer sb = new StringBuffer();
    //  Add functionality 
    sb.append("hello").append("world").append("java");
    System.out.println("sb:" + sb);
    // public StringBuffer deleteCharAt(int index): Deletes the character at the specified position and returns itself 
    //  Requirement: I want to delete e This character is swollen ?
    // sb.deleteCharAt(1);
    //  Demand : I want to delete the 1 A l This character is swollen ?
    // sb.deleteCharAt(1);
    // public StringBuffer delete(int start,int
    // end): Deletes content that starts at the specified location and ends at the specified location, and returns itself 
    //  Requirement: I want to delete world This string, is it swollen ?
    // sb.delete(5, 10);
    //  Demand : I want to delete all the data 
    sb.delete(0, sb.length());
    System.out.println("sb:" + sb);
  }
}

Replacements for StringBuffer:


package cn.itcast_04;
/*
 * StringBuffer Alternative features of: 
 * public StringBuffer replace(int start,int end,String str): From start Begin to end Use str Replace 
 */
public class StringBufferDemo {
  public static void main(String[] args) {
    //  To create a string buffer object 
    StringBuffer sb = new StringBuffer();
    //  Add data 
    sb.append("hello");
    sb.append("world");
    sb.append("java");
    System.out.println("sb:" + sb);
    // public StringBuffer replace(int start,int end,String
    // str): From start Begin to end Use str Replace 
    //  Requirement: I want to put world This data is replaced by " Happy holidays "
    sb.replace(5, 10, " Happy holidays ");
    System.out.println("sb:" + sb);
  }
}

Inversion function of StringBuffer:


package cn.itcast_05;
/*
 * StringBuffer Inversion function of: 
 * public StringBuffer reverse()
 */
public class StringBufferDemo {
  public static void main(String[] args) {
    //  To create a string buffer object 
    StringBuffer sb = new StringBuffer();
    //  Add data 
    sb.append(" Xia Qinglin loves me ");
    System.out.println("sb:" + sb);
    // public StringBuffer reverse()
    sb.reverse();
    System.out.println("sb:" + sb);
  }
}

Interception function of StringBuffer


package cn.itcast_06;
/*
 * StringBuffer Interception function of : Note that the return value type is no longer StringBuffer In itself 
 * public String substring(int start)
 * public String substring(int start,int end)
 */
public class StringBufferDemo {
  public static void main(String[] args) {
    //  To create a string buffer object 
    StringBuffer sb = new StringBuffer();
    //  Add Element 
    sb.append("hello").append("world").append("java");
    System.out.println("sb:" + sb);
    //  Interception function 
    // public String substring(int start)
    String s = sb.substring(5);
    System.out.println("s:" + s);
    System.out.println("sb:" + sb);
    // public String substring(int start,int end)
    String ss = sb.substring(5, 10);
    System.out.println("ss:" + ss);
    System.out.println("sb:" + sb);
  }
}

Interconversion between String and StringBuffer?


package cn.itcast_07;
/*
 *  Why do we want to explain the conversion between classes: 
 * A -- B Conversion of 
 *  We put A Convert to B In fact, it is for using B Function of. 
 * B -- A Conversion of 
 *  What we might want is A Type, so you have to turn it back. 
 * 
 * String And StringBuffer Mutual conversion of ?
 */
public class StringBufferTest {
  public static void main(String[] args) {
    // String -- StringBuffer
    String s = "hello";
    //  Note: You cannot assign the value of a string directly to StringBuffer
    // StringBuffer sb = "hello";// This is a mistake in writing 
    // StringBuffer sb = s;
    //  Mode 1: Through the construction method 
    StringBuffer sb = new StringBuffer(s);
    //  Mode 2 : Adopted append() Method 
    StringBuffer sb2 = new StringBuffer();
    sb2.append(s);
    System.out.println("sb:" + sb);
    System.out.println("sb2:" + sb2);
    System.out.println("---------------");
    // StringBuffer -- String
    StringBuffer buffer = new StringBuffer("java");
    // String(StringBuffer buffer)
    //  Mode 1: Through the construction method 
    String str = new String(buffer);
    //  Mode 2 : Adopted toString() Method 
    String str2 = buffer.toString();
    System.out.println("str:" + str);
    System.out.println("str2:" + str2);
  }
}

Splice arrays into 1 string using StringBuffer


package cn.itcast_07;
/*
 *  Splice arrays into 1 String 
 */
public class StringBufferTest2 {
  public static void main(String[] args) {
    //  Definition 1 Array of numbers 
    int[] arr = { 44, 33, 55, 11, 22 };
    //  Define functionality 
    //  Mode 1 : With String The way of splicing 
    String s1 = arrayToString(arr);
    System.out.println("s1:" + s1);
    //  Mode 2: Use StringBuffer The way of splicing 
    String s2 = arrayToString2(arr);
    System.out.println("s2:" + s2);
  }
  //  Use StringBuffer The way of splicing 
  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();
  }
  //  Use String The way of splicing 
  public static String arrayToString(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;
  }
}

Invert a string


package cn.itcast_07;
import java.util.Scanner;
/*
 *  Invert a string 
 */
public class StringBufferTest3 {
  public static void main(String[] args) {
    //  Keyboard entry data 
    Scanner sc = new Scanner(System.in);
    System.out.println(" Please enter data: ");
    String s = sc.nextLine();
    //  Mode 1 : With String Make splices 
    String s1 = myReverse(s);
    System.out.println("s1:" + s1);
    //  Mode 2 : With StringBuffer Adj. reverse() Function 
    String s2 = myReverse2(s);
    System.out.println("s2:" + s2);
  }
  //  Use StringBuffer Adj. reverse() Function 
  public static String myReverse2(String s) {
    return new StringBuffer(s).reverse().toString();
  }
  //  Use String Make splices 
  public static String myReverse(String s) {
    String result = "";
    char[] chs = s.toCharArray();
    for (int x = chs.length - 1; x >= 0; x--) {
      result += chs[x];
    }
    return result;
  }
}

Determine whether a string is a symmetric string


package cn.itcast_07;
import java.util.Scanner;
/*
 *  Judge 1 Is the string symmetrical 
 *  For example "abc" Is not a symmetric string, "aba" , "abba" , "aaa" , "mnanm" Is a symmetric string 
 * 
 *  Analysis: 
 *      Judge 1 If the string is a symmetrical string, I just need to put 
 *        No. 1 1 One and the last 1 A comparison 
 *        No. 1 2 Number and penultimate 2 A comparison 
 *       ...
 *      The number of comparisons is the length divided by the length 2 . 
 */
public class StringBufferTest4 {
  public static void main(String[] args) {
    //  Create keyboard entry objects 
    Scanner sc = new Scanner(System.in);
    System.out.println(" Please enter 1 String: ");
    String s = sc.nextLine();
    // 1 A 1 Comparison of 
    boolean b = isSame(s);
    System.out.println("b:" + b);
    // Use the inversion function of string buffer 
    boolean b2 = isSame2(s);
    System.out.println("b2:"+b2);
  }
  // Use the inversion function of string buffer 
  public static boolean isSame2(String s) {
    return new StringBuffer(s).reverse().toString().equals(s);
  }
  // 1 A 1 Comparison of 
  public static boolean isSame(String s) {
    boolean flag = true;
    //  Convert a string into an array of characters 
    char[] chs = s.toCharArray();
    for (int start = 0, end = chs.length - 1; start <= end; start++, end--) {
      if (chs[start] != chs[end]) {
        flag = false;
        break;
      }
    }
    return flag;
  }
}

What is the difference between String, StringBuffer and StringBuilder?


package cn.itcast_02;
/*
 * StringBuffer Add functionality to: 
 * public StringBuffer append(String str): You can add any type of data to the string buffer , And returns the string buffer itself 
 * 
 * public StringBuffer insert(int offset,String str): Inserts any type of data into the string buffer at the specified position , And returns the string buffer itself 
 */
public class StringBufferDemo {
  public static void main(String[] args) {
    //  To create a string buffer object 
    StringBuffer sb = new StringBuffer();
//     public StringBuffer append(String str)
     StringBuffer sb2 = sb.append("hello");
     System.out.println("sb:" + sb);
     System.out.println("sb2:" + sb2);
     System.out.println(sb == sb2); // true
    // 1 Step 1 Add data to step 
    // sb.append("hello");
    // sb.append(true);
    // sb.append(12);
    // sb.append(34.56);
    //  Chain programming 
    sb.append("hello").append(true).append(12).append(34.56);
    System.out.println("sb:" + sb);
    // public StringBuffer insert(int offset,String
    // str): Inserts any type of data into the string buffer at the specified position , And returns the string buffer itself 
    sb.insert(5, "world");
    System.out.println("sb:" + sb);
  }
}

0

More readers interested in java can check the topics of this site: "Summary of Java Character and String Operation Skills", "Summary of Java Array Operation Skills", "Summary of Java Mathematical Operation Skills", "Java Data Structure and Algorithm Tutorial" and "Summary of Java Operation DOM Node Skills"

I hope this article is helpful to everyone's java programming.


Related articles: