String class and StringBuffer class

Posted by MaTT on Sun, 09 Jan 2022 22:34:26 +0100

String class and StringBuffer class

Initialization of String class

  • Directly initialize a String object with a String constant

    String variable name = string;
    When initializing a string constant object, you can either set the initial value of the string object to null or initialize it to a specific string

String str1 = null; //Initialization is null
String str2 = ""; //Initialize to an empty string
String str3 = "abc"; //Initialize to abc, where abc is a string constant
  • Initializes a String object using the String constructor

    String variable name = new String("string");
    The string can be empty or a concrete string

Method declarationFunction description
String()Create a string with empty content
String(String value)Creates an object based on the specified string content
String(char[] value)Creates an object from the specified character array
//The following code is an example of the use of the three methods in the above table
public class Example01 {

    public static void main(String[] args) {

        String str1 = new String(); //Create an empty string

        String str2 = new String("abc"); //Create a string with abc content

        // Create a string with an array of characters
        char[] charArray = new char[] {'a', 'b', 'c'};

        String str3 = new String(charArray);

        //Output results
        System.out.println("a" + str1 + "b");
        //Tips: in Java, if one of the operands on both sides of + is of String type, then + represents String concatenation operator

        System.out.println(str2);

        System.out.println(str3);
    }
}

Common operations of String class

Method declarationFunction description
int indexOf(int ch)Returns the index of the first occurrence of the specified character in this string
int lastIndexOf(int ch)Returns the index of the last occurrence of the specified string in this string
int indexOf(String str)Returns the index of the first occurrence of the specified string in this string
char charAt(int index)Returns the character at the index position in the string, where the value range of index is 0 ~ string length - 1
boolean endsWith(String suffix)Determines whether this string ends with the specified string
int length()Returns the length of the string
boolean equals(Object anObject)Compares this string with the specified string
boolean isEmpty()Returns true if and only if the string length is 0
boolean startWith(String prefix)Determines whether this string starts with the specified string
boolean contains(CharSequence cs)Determines whether the string contains the specified character sequence
String toLowerCase()Converts all characters in a String to lowercase using the rules of the default locale
String toUpperCase()Converts all characters in a String to uppercase using the rules of the default locale
static String valueOf(int t)Returns the string representation of the int parameter
char[] toCharArray()Converts this string to an array of characters
String replace(CharSequence oldStr, CharSequence newStr)Returns a new string obtained by replacing all oldstrs in this string with newStr
String[] split(Strng regex)According to the parameter regex(regex is a regular expression that defines the separation rule)
String substring(int beginIndex)Returns a new string containing all characters starting at the specified beginIndex starting angle and ending at the end of the string
String substring(int beginIndex, int endIndex)Returns a new string that contains all characters from the specified beginIndex start corner to the index endIndex-1 corner
String trim()Returns a new string, which removes the spaces at the beginning and end of the original string

Tips: About why indexOf(int ch) uses int type as parameter

  • Basic operation of string
public class Example02 {

    public static void main(String[] args) {

        String s = "abcabcabcdba"; //Initialization string

        System.out.println("String length is:" + s.length());

        System.out.println("First character in string:" + s.charAt(0));

        System.out.println("character c Location of the first occurrence:" + s.indexOf('c'));

        System.out.println("character c Location of the last occurrence:" + s.lastIndexOf('c'));

        System.out.println("The position where the substring first appears:" + s.indexOf("ab"));

        System.out.println("The last occurrence of the substring:" + s.lastIndexOf("ab"));
    }
}
  • String conversion
public class Example03 {

    public static void main(String[] args) {

        String str = "java";

        char[] charArray = str.toCharArray(); //Convert string to character array

        System.out.print("Turns a string into a traversal result of a character array:");

        for(int i = 0; i < charArray.length; i++) {

            if(i != charArray.length-1) {
                //If it is not the last element of the array, add a comma after the element
                System.out.print(charArray[i] + ",");
            } else {

                //The last element of the array is not followed by a comma
                System.out.println(charArray[i]);
            }
        }

        System.out.println("take int Convert value to String Results after type:" + String.valueOf(12));
        //String.valueOf() converts an int type integer to a string

        System.out.println("The result of converting a string to uppercase:" + str.toUpperCase());
    }
}
  • String replacement and space removal operations
public class Example03 {

    public static void main(String[] args) {

        String str1 = " https: //www.pronhub.com ";

        System.out.println("Result after removing spaces at both ends of the string:" +str1.trim());
        // Output "https: //www.pornhub.com"

        System.out.println("The result after removing all spaces in the string:" +str1.replace(" ", ""));
        // Output“ https://www.pronhub.com "
    }
}
  • String judgment operation
public class Example05 {

    public static void main(String[] args) {

        String s1 = "Starter"; //Declare a string

        String s2 = "St";

        System.out.println("s1 Whether to St start:" + s1.startsWith("St"));

        System.out.println("s1 Whether to er ending:" + s1.endsWith("er"));

        System.out.println("s1 Include ar:" + s1.contains("ar"));

        System.out.println("s1 Is it empty" + s1.isEmpty());

        System.out.println("s1 And s2 Are the strings equal" + s1.equals(s2));
        /** "=="And "equals()"
         * equals() Used to compare whether the values of two objects are equal
         * == Used to compare whether the memory addresses of two objects are equal
         **/

    }
}
  • String interception and segmentation
public class Example06 {

    public static void main(String[] args) {

        String str = "2022-1-6";

        System.out.println("The result truncated from the 6th character to the end:" + str.substring(5));

        System.out.println("The result intercepted from the 6th character to the 7th character:" + str.substring(5, 7));
        
        System.out.println("The elements in the split string array are:");

        String[] strArray = str.split("-");

        for(int count = 0; count < strArray.length; count++) {

            if(count != strArray.length-1) {
                
                System.out.print(strArray[count] + ".");

            }else{

                System.out.println(strArray[count]);
            }

        }
    }
}

Tips: String string string the index of the string will be used when obtaining a character. When accessing a character in the string, if the index does not exist, stringindexoutofboundsexception (string corner out of bounds exception) will occur

StringBuffer class

In Java, the String class is final. The String defined by String is a constant. Once established, its content and length cannot be changed

To facilitate string modification, a StringBuffer class (string buffer) is provided in the JDK to manipulate strings. The string defined by the StringBuffer class (similar to a character container) has variable content and length

Method declarationFunction description
StringBuffer append(char c)Adds a character to the end of the StringBuffer object
StrigBuffer insert(int offset, String str)Insert the string str at the offset position in the StringBuffer object
StringBuffer deleteCharAt(int index)Removes the character at the specified position from the StringBuffer object
StringBuffer delete(int start, int end)Removes the specified range of characters or strings from the StringBuffer object
StringBuffer replace(int start, int end, String s)Replace the specified range of characters or strings in the StringBuffer object with s
void setCharAt(int index), char chModify the character at the specified position
String toString()Returns the string object in the StringBuffer buffer
StringBuffer revese()Replace this StringBuffer object with its inverted form
public class Example08 {

    public static void main(String[] args) {

        System.out.println("1.add to--------------------------");

        add();

        System.out.println("2.modify--------------------------");

        update();

        System.out.println("3.delete--------------------------");

        delete();
    }

    public static void add() {
        
        StringBuffer sb = new StringBuffer(); //Define a string buffer

        sb.append("ABC"); //Add string

        System.out.println("append Add results:" + sb);

        sb.insert(3, "DE"); //Inserts a string at the specified location

        System.out.println("insert Add results:" + sb);
    }

    public static void update() {

        StringBuffer sb = new StringBuffer("ABAAA");

        sb.setCharAt(2, 'C'); //Modify character at specified position

        sb.replace(3, 5, "DE"); //Replace the specified location string

        System.out.println("Replace specified location results:" + sb);

        System.out.println("String flip result:" + sb.reverse());
    }

    public static void delete() {

        StringBuffer sb = new StringBuffer("ABCDEFG");

        sb.delete(3, 7);

        System.out.println("Deletes the string result of the specified range:" + sb);

        sb.deleteCharAt(2);

        System.out.println("Deletes the string result at the specified location:" + sb);

        sb.delete(0, sb.length());

        System.out.println("Empty buffer result:" + sb);
    }
}

Pay more attention to:

  1. The String defined by the String class is a constant. Once created, its content and length cannot be changed StringBuffer represents a character container whose content and length can be modified at any time
  2. String class overrides the equals() method of Object class, while StringBuffer class does not override the equals() method of Object class The equals() method of string class compares values, and the equals() method of StringBuffer class compares memory addresses
  3. String objects can be connected by the operator "+", while StringBuffer objects cannot be connected
  • StringBuilder class

JDK1. After 5, a StringBuilder class is provided, which is similar to StringBuffer
StringBuilder (asynchronous) does not implement thread safety, so its performance is slightly higher StringBuffer (synchronization) is thread safe
Synchronization: execute in sequence, step by step (synchronous)
Asynchronous: take a task and send it directly to the background. In the next task, whoever reads it first will execute it first. There is no order, which may lead to the following code before the above code comes out
When creating a string object with variable content, the StringBuffer class is preferred

Topics: Java Back-end