StringBuffer and StringBuilder classes in java

table of Contents

Create StringBuffer class

Additional character skewer

Replacement character

Reverse string

Delete string

StringBuffer method


In  Java  , in addition to creating and processing strings through the String class, you can also use the StringBuffer class to process strings. The StringBuffer class can handle strings more efficiently than the String class.

When modifying a string, you need to use the StringBuffer and StringBuilder classes.

Different from the String class, objects of the StringBuffer and StringBuilder classes can be modified multiple times without generating new unused objects.

The StringBuilder class was proposed in Java 5. The biggest difference between it and StringBuffer is that the methods of StringBuilder are not thread-safe (cannot be accessed synchronously).

Because StringBuilder has a speed advantage compared to StringBuffer , it is recommended to use StringBuilder class in most cases . However, if the application requires thread safety, the StringBuffer class must be used .


Because the  StringBuffer class is a variable string class, you can modify the content of the string at will after creating an object of the StringBuffer class. Each StringBuffer class object can store a string of a specified capacity. If the length of the string exceeds the capacity of the StringBuffer class object, the capacity of the object will automatically expand.

Create StringBuffer class

The StringBuffer class provides 3 construction methods to create a string, as shown below:

  • StringBuffer() constructs an empty string buffer and is initialized to a capacity of 16 characters.
  • StringBuffer(int length) creates an empty string buffer and initializes it to the capacity of the specified length.
  • StringBuffer(String str) creates a string buffer and initializes its content to the specified string content str. The initial capacity of the string buffer is 16 plus the length of the string str.


An example of using the constructor of the StringBuffer class is as follows:

 

// 定义一个空的字符串缓冲区,含有16个字符的容量
StringBuffer str1 = new StringBuffer();

// 定义一个含有10个字符容量的字符串缓冲区
StringBuffer str2 = new StringBuffer(10);

// 定义一个含有(16+4)的字符串缓冲区,"青春无悔"为4个字符
StringBuffer str3 = new StringBuffer("青春无悔");
/*
*输出字符串的容量大小
*capacity()方法返回字符串的容量大小
*/
System.out.println(str1.capacity()); // 输出 16
System.out.println(str2.capacity()); // 输出 10
System.out.println(str3.capacity()); // 输出 20


The above code declares three StringBuffer objects str1, str2 and str3, and initializes them respectively. str1.capacity() is used to check the capacity of str1, and then check the capacity of str2 and str3 in the same way.

Additional character skewer

The append() method of the StringBuffer class is used to append a string to the original StringBuffer object. The syntax format of this method is as follows:

StringBuffer 对象.append(String str)


The function of this method is to append content to the end of the current StringBuffer object, similar to the connection of strings. After calling this method, the content of the StringBuffer object has also changed, for example:

 
StringBuffer buffer = new StringBuffer("hello,"); // 创建一个 StringBuffer 对象
String str = "World!";
buffer.append(str); // 向 StringBuffer 对象追加 str 字符串
System.out.println(buffer.substring(0)); // 输出:Hello,World!

 

Example 1

At the beginning of each new semester, the school will list the required courses for the courses of this semester. Write a Java program that requires the user to enter the names of five required courses into the console, connect the five names, and finally output the connected string. code show as below:

 
  1. import java.util.Scanner;
    public class Testl9 {
    public static void main(String[] args) {
    StringBuffer sys = new StringBuffer("校内课程管理");
    System.out.println("欢迎进入《"+sys+"》系统");
    // 声明课程名称字符串
    StringBuffer courseName = new StringBuffer();
    System.out.println("请录入本期的五门必修课名称:");
    Scanner input = new Scanner(System.in);
    // 循环接收控制台输入的字符串
    String name = "";
    for (int i = 0;i < 5;i++) {
    name = input.next();
    courseName.append(name+"\t");
    if(i == 4) {
    System.out.println("录入完毕!");
    }
    }
    System.out.println("本学期的必修课程有:\n"+courseName);
    }

     


In this program, first declare an empty StringBuffer object, and then declare and initialize the courseName variable, which is used to store the course name entered by the user from the console, and then use a for loop statement to cyclically receive user input data. In the loop body, the append() method of the StringBuffer object is called to append the string entered by the user. After the user has recorded the names of the five courses, the program will output the prompt message "Entry completed!" Finally, output the String-Buffer object string.

Run the program, the execution result is as follows:

欢迎进入《校内课程管理》系统
请录入本期的五门必修课名称:
Java语言基础
SQL查询数据库
模拟电路
Java面向对象编程
体育
录入完毕!
本学期的必修课程有:Java语言基础  SQL查询数据库  模拟电路  Java面向对象编程  体育

Replacement character

The setCharAt() method of the StringBuffer class is used to replace a character at the specified index position of the string. The syntax format of this method is as follows:

StringBuffer 对象.setCharAt(int index, char ch);


The function of this method is to modify the character at the index position in the object to the new character ch, for example:

StringBuffer sb = new StringBuffer("hello");
sb.setCharAt(1,'E');
System.out.println(sb); // 输出:hEllo
sb.setCharAt(0,'H');
System.out.println(sb); // 输出:HEllo
sb.setCharAt(2,'p');
System.out.println(sb); // 输出:HEplo

Reverse string

The reverse() method in the StringBuffer class is used to replace the string sequence with its reversed form. The syntax format of this method is as follows:

StringBuffer 对象.reverse();


An example of using the reverse() method in the StringBuffer class to reverse a string is as follows:

 
StringBuffer sb = new StringBuffer("java");
sb.reverse();
System.out.println(sb); // 输出:avaj

Delete string

The StringBuffer class provides deleteCharAt() and delete() two methods to delete strings, which are described in detail below.

1. deleteCharAt() method

The deleteCharAt() method is used to remove the character at the specified position in the sequence. The syntax format of this method is as follows:

StringBuffer 对象.deleteCharAt(int index);

The function of the deleteCharAt() method is to delete the character at the specified position, and then form the remaining content into a new string. E.g:


StringBuffer sb = new StringBuffer("She");
sb.deleteCharAt(2);
System.out.println(sb); // 输出:Sh


Execute this code to delete the character whose index value is 2 in the string sb, and the remaining content forms a new string, so the value of the object sb is Sh.

2. delete() method

The delete() method is used to remove the characters of the substring in the sequence. The syntax of the method is as follows:

StringBuffer 对象.delete(int start,int end);

Among them, start represents the starting index value of the character to be deleted (including the character corresponding to the index value), and end represents the end index value of the character string to be deleted (not including the character corresponding to the index value). The function of this method is to delete all characters within the specified area, for example:


StringBuffer sb = new StringBuffer("hello jack");
sb.delete(2,5);
System.out.println(sb); // 输出:he jack
sb.delete(2,5);
System.out.println(sb); // 输出:heck

Execute this code to delete all characters from the string "hello jack" with an index value of 2 (inclusive) to an index value of 5 (exclusive), so the value of the new output string is "he jack".

 

StringBuffer method

The following are the main methods supported by the StringBuffer class:

Serial number Method description
1 public StringBuffer append(String s)
appends the specified string to this character sequence.
2 public StringBuffer reverse()
 replaces this character sequence with its reversed form.
3 public delete(int start, int end)
removes the characters in the substring of this sequence.
4 public insert(int offset, int i)
inserts  int the string representation of the parameter into this sequence.
5 replace (int start, int end, String str)
given  String characters replacing substrings of this sequence of characters.

The methods in the following list are similar to those of the String class:

Serial number Method description
1 int capacity()
returns the current capacity.
2 char charAt(int index)
returns the char value at the specified index in this sequence  .
3 void ensureCapacity(int minimumCapacity)
ensures that the capacity is at least equal to the specified minimum.
4 void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
copies the characters from this sequence to the target character array  dst.
5 int indexOf(String str)
returns the index of the first occurrence of the specified substring in the string.
6 int indexOf(String str, int fromIndex)
starts at the specified index and returns the index of the first occurrence of the specified substring in the string.
7 int lastIndexOf(String str)
returns the index of the specified substring that appears on the far right in this string.
8 int lastIndexOf(String str, int fromIndex)
returns the last occurrence position of the substring in the String object.
9 int length()
 returns the length (number of characters).
10 void setCharAt(int index, char ch)
sets the character at the given index to  ch.
11 void setLength(int newLength)
sets the length of the character sequence.
12 CharSequence subSequence(int start, int end)
returns a new character sequence which is a subsequence of this sequence.
13 String substring(int start)
returns a new one  Stringthat contains the character subsequence currently contained in this character sequence.
14 String substring(int start, int end)
返回一个新的 String,它包含此序列当前所包含的字符子序列。
15 String toString()
返回此序列中数据的字符串表示形式。

Guess you like

Origin blog.csdn.net/q1246192888/article/details/107848172