2021-09-02 sorting out string & StringBuilder & StringBuffer knowledge points

Posted by lisa99 on Fri, 03 Sep 2021 08:35:18 +0200

String & StringBuilder & StringBuffer

String

1 String overview

  • The String class is under the java.lang package, so you don't need to import the package when using it
  • String class represents string. All string literals (such as "a,b,c") in Java programs are implemented as examples of this class. Simple understanding: all double quoted strings in Java programs are objects of string class
  • Strings are immutable and their values cannot be changed after creation

2. Common construction methods of string

Method nameexplain
public String()Create a blank string object that contains nothing
public String(char[] chs)Convert a character array into a corresponding string object
public String(char[] chs,int startIndex, int count)Converts a part of a character array into a corresponding string object
public String;(String s)Encapsulate a string object into a string object. For example: String s = new String("abc")
String s = "abc"The method of direct assignment creates a string object, the content of which is abc

3. The difference between the two methods of creating string objects

  • Construction method creation: for string objects created through new, each new will open up new memory. Although the contents are the same, the address values are different
  • Create by direct assignment: as long as the character sequence of the String given in double quotation marks is the same, no matter how many times it appears in the program code, the JVM will only create a String object and maintain it in the String pool

4 Comparison of differences in creating string objects

  • Note: = = for comparison

    Basic data type: compares specific values

    [the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-RyrBQgwS-1630581895410)(C:\Users198\Pictures\Saved Pictures\String basic data type create object. png)]

    Reference data type: compare address values

    [the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-dzKbPJKP-1630581895413)(C:\Users198\Pictures\Saved Pictures\String reference data type to create an object. png)]

5. Characteristics of string

  • All double quoted strings in Java programs are objects of the String class
  • Strings are immutable and their values cannot be changed after creation
  • Although String values are immutable, they can be shared

6 member method of string class

Method nameexplain
public boolean equals(String anObject)Compare this string with the specified object, case sensitive
public boolean equalsIgnoreCase(String anotherString)Compare this String with another String, regardless of case.
public char charAt(int index)Returns the char value at the specified index
public int length()Returns the length of this string
public char[] toCharArray()Converts this string to a new character array
public String substring(int beginIndex)Intercept backward from the passed in index position to the end to get a new string and return it
public String substring(int beginIndex, int endIndex)Intercept from the beginIndex index position, intercept to the endIndex index position, get a new string and return it (including the header and excluding the tail)
String[] split(String regex)Cut according to the incoming string as a rule, store the cut content in the string array, and return the string array

7. Some code display of string class

7.1.1 case requirements

Known user name and password, please use the program to simulate user login.
A total of three failure opportunities are given. After logging in, corresponding prompts are given

7.1.2 code implementation

public class StringTest {
    public static void main(String[] args) {
        //  1. If the user name and password are known, define two string representations
        String username = "zhangsan";
        String password = "123456";

        //  2. Enter the user name and password to log in with the keyboard, which is implemented with Scanner
        Scanner sc = new Scanner(System.in);

        for (int i = 1; i <= 3; i++) {
            System.out.println("Please enter the user name you entered:");
            String user = sc.nextLine();
            System.out.println("Please enter the password you entered:");
            String pwd = sc.nextLine();

            if (username.equals(user) && password.equals(pwd)) {
                System.out.println("Login succeeded!");
                break;// Stop cycle
            } else {
                if (3 - i == 0) {
                    System.out.println("Account lock,Please try again tomorrow!");
                } else {
                    System.out.println("Login failed!You have" + (3 - i) + "Second chance");
                }
            }
        }
    }

    public static void method() {
        String s = "abCd";
        // public boolean equals(String s): compares this string with the specified object. Strictly case sensitive
        System.out.println(s.equals("abCd"));// true
        System.out.println(s.equals("abcd"));// false

        // public boolean equalsIgnoreCase(String s): compares this string with the specified object. ignore case
        System.out.println(s.equalsIgnoreCase("abCd"));// true
        System.out.println(s.equalsIgnoreCase("abcd"));// true
    }
}

7.2.1 case requirements

Enter a string on the keyboard and count the uppercase and lowercase characters in the string,
Number of occurrences of numeric characters (regardless of other characters)

7.2.2 code implementation

public class StringTest {
    public static void main(String[] args) {
        // 1. Enter a string on the keyboard and implement it with Scanner
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter a string:");
        String s = sc.nextLine();//

        // 2. To count the number of three types of characters, you need to define three statistical variables with initial values of 0
        int bigCount = 0;// Record the number of occurrences of capital letters
        int smallCount = 0;// Record the number of occurrences of lowercase letters
        int numberCount = 0;// Record the number of occurrences of the number

        // 3. Traverse the string to get each character
        for (int i = 0; i < s.length(); i++) {
            // Get each character according to the index
            char ch = s.charAt(i); // '1'
            if (ch >= 'a' && ch <= 'z') {
                smallCount++;
            } else if (ch >= 'A' && ch <= 'Z') {
                bigCount++;
            } else if (ch >= '0' && ch <= '9') {
                numberCount++;
            }
        }
        System.out.println("The number of lowercase letters is:" + smallCount);
        System.out.println("The number of times uppercase letters appear is:" + bigCount);
        System.out.println("The number of occurrences is:" + numberCount);
    }
}

7.3.1 case requirements

Accept a mobile phone number from the keyboard in the form of string, and shield the middle four numbers
The final effect is: 156 * * * * 1234

7.3.2 code implementation

public class StringTest {
    public static void main(String[] args) {
        //  1. Enter a string on the keyboard and implement it with Scanner
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter your mobile phone number:");
        String phoneNumber = sc.nextLine();// 15600011234

        // 2. Intercept the first three digits of the string
        String start = phoneNumber.substring(0, 3);

        // 3. Intercept the last four digits of the string
        String end = phoneNumber.substring(7);

        // 4. Splice the two intercepted strings with * * * * in the middle to output the result
        System.out.println(start + "****" + end);
    }

    public static void method() {
        String s = "abcdfghjkl";
        //  public String substring(int beginIndex): intercept backward from the passed in index position until the end to get a new string and return it
        String newStr = s.substring(4);
        System.out.println(newStr);// fghjkl

        // public String substring(int beginIndex, int endIndex): intercept from the beginIndex index position, intercept to the endIndex index position, get a new string and return it (including header and excluding tail)
        // String newStr2 = s.substring(5, 11);
        String newStr2 = s.substring(5, 8);
        System.out.println(newStr2);// ghj
    }

}

7.4.1 case requirements

Enter a string on the keyboard. If the string contains (TMD), use * * * instead

7.4.2 code implementation

import java.util.Scanner;
public class StringTest {
    public static void main(String[] args) {
        // Enter a string on the keyboard and implement it with Scanner
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter a string:");
        String s = sc.nextLine(); // "You TMD are really a talent!"

        String newStr = s.replace("TMD", "***");

        System.out.println(newStr);
    }



    public static void method() {
        String s = "abcasdbasdbasbd";

        // String replace(String target, String replacement)
        // Replace the target content in the current string with replacement to return a new string
        String newStr = s.replace("a", "*");
        System.out.println(newStr);

    }
}

7.5.1 case requirements

Enter student information from the keyboard in the form of string, for example: "Zhang San, 23"
Cut the valid data from the string and encapsulate it as a Student object

7.5.2 code implementation

/*
    Student class
 */
 public class Student {
    private String name;
    private String age;

    public Student() {
    }

    public Student(String name, String age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }
}
/*
    Student testing
 */
import java.util.Scanner;
public class StringTest {
    public static void main(String[] args) {
        // Enter a string on the keyboard and use Scanner to realize "Zhang San, 23"
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter student information:");
        String message = sc.nextLine();// "Zhang San, 23"

        String[] str = message.split(",");// {"Zhang San", "23"}

        // Creating objects: all parameter construction
        Student s = new Student(str[0] , str[1]);

        System.out.println("full name:" + s.getName());
        System.out.println("Age:" + s.getAge());

    }

    public static void method() {
        // String s = "11 22 33 44 55";
        // String s = "11.22.33.44.55";
        String s = "11+22+33+44+55";
        //  String[] split(String regex): cut according to the incoming string as a rule
        //  Store the cut content into the string array and return the string array
        String[] str = s.split("\\+");// {"11" , "22" ,"33" ,"44" ,"55"}

        // Traversal string array
        for (int i = 0; i < str.length; i++) {
            System.out.println(str[i]);
        }

    }
}

StringBuilder

1 StringBuilder overview

StringBuilder is a variable string class. We can think of it as a container

  • Function: improve the operation efficiency of string

2. StringBuilder construction method

Method nameexplain
public StringBuilder()Create an empty container that contains nothing
public StringBuilder(String str)Create a container with an initialization value based on the contents of the string

3 common methods of StringBuilder

Method nameexplain
Public StringBuilder append (any type)Add data and return the object itself
public StringBuilder reverse()Invert the data in the container and return the object itself
public int length()Return length (number of characters)
public String toString()You can convert StringBuilder to String by toString()

4. Principle of StringBuilder to improve efficiency

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-YOasAXWl-1630581895415)(C:\Users198\Pictures\Saved Pictures(.png)]

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-hfg31en-1630581895418) (C: \ users \ 12198 \ pictures \ saved pictures \ 2. PNG)]

5. Difference between StringBuilder and String

  • String: the content is immutable
  • StringBuilder: the content is mutable

6. Conversion between StringBuilder and String

  • Convert StringBuilder to String

    public String toString(): you can convert StringBuilder to String through toString()

  • Convert String to StringBuilder

    public StringBuilder(String s): you can convert a String into a StringBuilder by constructing a method

7. Some code display of StringBuilder class

7.1.1 case requirements

The keyboard accepts a string, the program determines whether the string is a symmetrical string, and prints yes or no on the console
Symmetric string: 123321, 111
Asymmetric string: 123123

7.1.2 code implementation

import java.util.Scanner;
public class StringBuilderTest1 {
    public static void main(String[] args) {
        //  1. Enter a string with the keyboard and implement it with Scanner
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter a string:");
        String s = sc.nextLine();
        checkString(s);
    }

    /*
        The function of the method is to receive a string and verify whether the string is symmetric data
        Two clear
            1 Return value type: void
            2 Parameter list: String s
     */
    public static void checkString(String s) {// s = "abc"
        // 2 reverse the string entered on the keyboard
        // String - > StringBuilder
        StringBuilder sb = new StringBuilder(s);// "cba"

        // reversal
        sb.reverse();

        // 3 use the inverted string to compare with the original string
        // StringBuilder --> String
        String ss = sb.toString();// "cba"

        if (s.equals(ss)) {
            System.out.println(s + "Is a symmetric data");
        } else {
            System.out.println(s + "Not a symmetric data");
        }
    }
}

7.2.1 case requirements

Define a method to splice the data in the int array into a string according to the specified format, call the method, and output the results on the console.
For example, the array is int[] arr = {1,2,3}; The output result after executing the method is: [1, 2, 3]

7.2.2 code implementation

public class StringBuilderTest2 {
    public static void main(String[] args) {
        // 1 define an array of type int, and use static initialization to complete the initialization of array elements
        int[] arr = {1, 2, 3};
        String s = getString(arr);
        System.out.println(s);
    }
    /*
        Method: receives an array and returns a string in the specified format
        Return value type: String
        Parameter list: int[] arr

        Splicing result [element, element, element... Element]
     */
    public static String getString(int[] arr) {
        // In the method, use StringBuilder to splice as required, and convert the result into String to return
        StringBuilder sb = new StringBuilder();
        sb.append("[");

        // Traverse the array to get each element in the array
        for (int i = 0; i < arr.length; i++) {
            if (i == arr.length - 1) {
                // Last element
                sb.append(arr[i]).append("]"); //Chained programming: you can use chained programming as long as the calling member returns an object
            } else {
                // Not the last element
                sb.append(arr[i]).append(",");
            }
        }
        // Convert StringBuilder to String and return
        return sb.toString();
    }
}

Relationship between StringBuffer and StringBuilder

  • StringBuffer class: data security cannot be guaranteed in multithreading, so it is used in single thread with high efficiency

  • StringBuilder class: it can ensure data security and can be used in multithreading. The efficiency of single thread is lower than that of StringBuilder ## title

Topics: Java