String class of common APIs (day 13 of learning Java)

catalogue

I Overview of String class

II Immutability of String class

III The difference between the two methods of creating string objects

4, Introduction to common string methods

1. = = comparison operator

2. equals method

3. equalsIgnoreCase method

4, concat(); Splice the two strings to get a new string

5,★length(); Get the length of the string (in fact, get the number of characters in the string)

6, ★charAt(); Get the character of the corresponding position according to the given index

7, ★indexOf(); Gets the position (index) of the first occurrence of the specified character in the string. If it is not found, it returns - 1 / / int index = A1 indexOf('h'); Find from the beginning, where 'H' first appears / / int index = A1 indexOf('h',3); Start with the element with index 3 and look back where 'H' first appears

8,lastIndexOf(); Gets the position (index) of the last occurrence of the specified character in the string. If it is not found, it returns - 1 / / int index = A1 lastIndexOf('h'); Find the position where 'H' last appears from the tail / / int index = A1 lastIndexOf('h',3); Look forward from the element with index 3, where 'H' last appeared

9, ★substring(); Intercept the string and return a new string / / string newstr = A1 substring(2); / / intercept the given index directly to the end of the string / / string newstr = A1 substring(2,5); / / the left side of the package is not the right side (the front is closed and the back is open). You can get the elements of index 2, not index 5

10, ★isEmpty(); Judge whether the string is empty (return true if the length is 0, and false if it is not 0)

11,     ★contains(); Determines whether the given string is included in the string.

12, endsWith(); Determines whether the string ends with the given string.

13, startsWith(); Determines whether the string starts with the given string.

   14, ★replace(); Replace the old content with the new content and return a new string

15,    toLowerCase(); / / convert all letters to their corresponding lowercase form.

16,toUpperCase(); / / convert all letters to their corresponding uppercase form.

17. toCharArray() / / convert string to array

18. getBytes() / / convert string to byte array

19,    ★trim(); / / remove the leading and trailing spaces.

20,★split(); / / cut the string according to the given content and return the string array

I Overview of String class

  • String is a final class and cannot be inherited; Represents an immutable character sequence. Abbreviation: non variability.
  • A string is a constant, expressed in double quotation marks. Their values cannot be changed after creation
  • The character content of the String object is stored in a character array value []

II Immutability of String class

  • When the string is re assigned, the assigned memory area needs to be rewritten, and the original value cannot be used
  • When connecting an existing string, you need to assign a new value to the memory area. You cannot use the original value
  • A string is assigned a literal value (different from new), and the string value is declared in the constant pool
  • Strings with the same content will not be stored in the constant pool

III The difference between the two methods of creating string objects

  • Create through construction method: for string objects created through new, each new will apply for a memory space. Although the string contents are the same, the address values are different
  • Create by direct assignment: as long as the character sequence is the same (order and case), no matter how many times it appears in the program code, the JVM will only create a String object and maintain it in the constant pool

be careful:

    • The splicing results of constants and constants are in the constant pool. And constants with the same content will not exist in the constant pool.
    • As long as one of them is a variable, the result is in the heap.

4, Introduction to common string methods

1. = = comparison operator

The basic data type compares whether the values of the two variables are the same.

The reference data type compares whether the address values of the two objects are the same.

2. equals method

public boolean equals(String s) compares whether the contents of two strings are the same and case sensitive

Compare whether the contents of two strings are the same, case sensitive, return true if they are the same, and false if they are different.

3. equalsIgnoreCase method

Public Boolean equalsignorecase (string otherstring): compares this string with the specified object, ignoring case.

Summary:

  • Compare whether the String contents are equal and case sensitive. You need to use the equals method of String class. Never use = = for comparison

  • If you compare whether the contents of strings are equal and case insensitive, you need to use the equalsIgnoreCase() method of the String class

4, concat(); Splice the two strings to get a new string

5,★length(); Get the length of the string (in fact, get the number of characters in the string)

6, ★charAt(); Get the character of the corresponding position according to the given index

7, ★indexOf(); Gets the position (index) of the first occurrence of the specified character in the string. If not found, return - 1
            //int index = a1.indexOf('h'); Look from the beginning, where 'H' first appears
            //int index = a1.indexOf('h',3); Start with the element with index 3 and look back where 'H' first appears

8,lastIndexOf(); Gets the position (index) of the last occurrence of the specified character in the string. If not found, return - 1
            //int index = a1.lastIndexOf('h'); Find the last position of 'H' from the tail
            //int index = a1.lastIndexOf('h',3); Look forward from the element with index 3, where 'H' last appeared

9, ★substring(); Intercepts the string and returns a new string
                    //String newStr = a1.substring(2); / / directly intercept from the given index to the end of the string
                    //String newStr = a1.substring(2,5); / / the left side of the package is not the right side (the front is closed and the back is open). You can get the elements of index 2, not index 5

10, ★isEmpty(); Judge whether the string is empty (return true if the length is 0, and false if it is not 0)

11,     ★contains(); Determines whether the given string is included in the string.

12, endsWith(); Determines whether the string ends with the given string.

13, startsWith(); Determines whether the string starts with the given string.

   14, ★replace(); Replace the old content with the new content and return a new string

15,    toLowerCase(); / / convert all letters to their corresponding lowercase form.

16,toUpperCase(); / / convert all letters to their corresponding uppercase form.

17. toCharArray() / / convert string to array

18. getBytes() / / convert string to byte array

19,    ★trim(); / / remove the leading and trailing spaces.

20,★split(); / / cut the string according to the given content and return the string array

public class Test {
    public static void main(String[] args) {
        /*
            ★boolean isEmpty(); //Judge whether the string is empty (if the length is 0, return true, if not 0, return false)
            ★boolean contains(CharSequence s);    //Determines whether the given string is included in the string.
            endsWith(); //Determines whether the string ends with the given string.
            startsWith(); //Determines whether the string starts with the given string.

            ★replace(); //Replace the old content with the new content and return a new string
            toLowerCase();  //Turn all letters into their corresponding lowercase form.
            toUpperCase();  //Turn all the letters into their corresponding capitals.
            toCharArray() // Convert string to array
            getBytes() // Convert string to byte array
            ★trim();            //Remove leading and trailing spaces.
            ★split();   //According to the given content, cut the string and return the string array
         */
        // isEmpty(); // Judge whether the string is empty (if the length is 0, return true, if not 0, return false)
        String str1 = null;// Empty means nothing
        String str2 = "";// Empty string object
        String str3 = " ";// String object with one space character
        //System.out.println(str1.isEmpty());//  Null pointer exception is reported because null cannot call method
        System.out.println(str2.isEmpty());// true
        System.out.println(str3.isEmpty());// false

        System.out.println("=========================");

        String str = "itheima-itcast";
        // boolean contains(CharSequence s);    // Determines whether the given string is included in the string
        // Requirement: judge whether the str string contains itcast
        System.out.println(str.contains("itcast"));// true
        System.out.println(str.contains("itcasts"));// false

        System.out.println("=========================");

        // boolean endsWith(String subff); // Determines whether the string ends with the given string.
        String fileName = "Test.java";
        System.out.println(fileName.endsWith(".java"));// true
        System.out.println(fileName.endsWith(".txt"));// false

        // startsWith(); // Determines whether the string starts with the given string.
        System.out.println(fileName.startsWith("Test"));// true
        System.out.println(fileName.startsWith("Demo"));// false

        System.out.println("=========================");

        // ★String replace(CharSequence target, CharSequence replacement); // Replace the old content with the new content and return a new string
        String message = "Ah, trump, ah, Trump----Trump";
        // Demand: replace trump with***
        String msg = message.replace("Trump", "***");
        System.out.println("Original string:"+message);// Ah, trump, ah, trump -- trump
        System.out.println("New string:"+msg);// Ah ah * * * ah ah***----***

        System.out.println("=========================");

        // toLowerCase();  // Turn all letters into their corresponding lowercase form.
        String str4 = "aBcD";
        String s4 = str4.toLowerCase();
        System.out.println("s4:"+s4);// abcd

        // toUpperCase();  // Turn all the letters into their corresponding capitals.
        String s5 = str4.toUpperCase();
        System.out.println("s5:"+s5);// ABCD

        // toCharArray() / / convert string to array
        char[] chs = str4.toCharArray();
        for (int i = 0; i < chs.length; i++) {
            System.out.println(chs[i]);// a   B   c   D
        }

        System.out.println("=========================");

        // getBytes() / / convert string to byte array
        byte[] bytes = str4.getBytes();
        for (int i = 0; i < bytes.length; i++) {
            System.out.println(bytes[i]);// 97,66,99,68
        }

        System.out.println("=========================");

        // ★trim();            // Remove leading and trailing spaces.
        String username = "  zhangsan  ";
        String name = username.trim();
        System.out.println("==="+name+"===");

        System.out.println("=========================");

        // ★String[] split(String regex);   // According to the given content, cut the string and return the string array
        // Basic usage: pass in an ordinary string without special meaning
        String str5 = "itcast,itheima,boxuegu";
        // Specifies to cut the string by comma
        String[] arr = str5.split(",");
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }

        System.out.println("=========================");
        // Advanced usage: pass in a string with special meaning, which is actually a regular expression
        String str6 = "abc bcd     cba              nba";
        String[] arr2 = str6.split(" +");
        System.out.println(arr2.length);
        for (int i = 0; i < arr2.length; i++) {
            System.out.println(arr2[i]);
        }

        System.out.println("=========================");
        String str7 = "abc.cba.nba.bac";
        String[] arr3 = str7.split("\\.");
        System.out.println(arr3.length);
        for (int i = 0; i < arr3.length; i++) {
            System.out.println(arr3[i]);
        }
        
    }
}

Keywords: Java Back-end

Added by proxydude on Mon, 10 Jan 2022 14:30:51 +0200