【Java】Understanding the String class


1. The Importance of String Class

Strings are already involved in C language, but in C language, you can only use character arrays or character pointers to represent strings. You can use the string series functions provided by the standard library to complete most operations, but this way of combining data and The separation of data manipulation methods does not conform to object-oriented thinking, and strings are widely used, so the Java language specifically provides the String class

2. Commonly used methods in the String class

1. String construction

The String class provides many construction methods, and the following three are commonly used:

public class Test {
    
    
    public static void main(String[] args) {
    
    
        String s = "hello";
        System.out.println(s);
        String s1 = new String("hello");
        System.out.println(s1);
        char[] s3 = {
    
    'h','e','l','l','o'};
        System.out.println(s3);
    }
}

Insert image description here
Note:
1. The String class is a reference type and does not store the string itself internally
2. Caused by "" in Java What comes is also a String type object

2. Comparison of String objects

Java provides four comparison methods:
1.==Compare whether the same object is referenced

public class Test {
    
    
    public static void main(String[] args) {
    
    
        int a = 10;
        int b = 20;
        int c = 10;
        System.out.println(a==b);
        System.out.println(a==c);
        System.out.println("********");
        String s = new String("hello");
        String s1 = new String("hello");
        String s2 = new String("word");
        String s3 = s;
        System.out.println(s==s1);
        System.out.println(s1==s2);
        System.out.println(s==s3);
    }
}

Insert image description here
Note: For built-in types, == compares the value in the variable; for reference types == compares the address in the reference

2.boolean equals(Object anObject) method: Compare in dictionary order
Dictionary order: character size order
The String class overrides the parent The equals method in class Object. By default, equals in Object compares according to ==. After String overrides the equals method, it compares according to the following rules

public class Test {
    
    
    public static void main(String[] args) {
    
    
        String s = new String("hello");
        String s1 = new String("hello");
        String s2 = new String("Hello");
        // equals比较:String对象中的逐个字符
        // s与s2引用的不是同一个对象,而且两个对象中内容也不同,因此输出false
         // s与s1引用的不是同一个对象,但是两个对象中放置的内容相同,因此输出true
        System.out.println(s.equals(s2));
        System.out.println(s.equals(s1));
    }
}

Insert image description here
3.int compareTo(String s) method: Compare in dictionary order
The difference from equals is that equals returns a boolean type, while compareTo returns an int type. Specific comparison method:
1. First compare the size according to dictionary order. If unequal characters appear, directly return the size difference of the two characters.
2. If the first k characters are equal (k is the minimum length of two characters), the return value is the difference between the lengths of the two strings

public class Test {
    
    
    public static void main(String[] args) {
    
    
        String s = new String("abc");
        String s1 = new String("ac");
        String s2 = new String("abc");
        String s3 = new String("abcde");
        System.out.println(s.compareTo(s1));//不同输出字符的差值为-1
        System.out.println(s.compareTo(s2));//输出字符相同为0
        System.out.println(s.compareTo(s3));//前几个字符相同,输出长度差值为-2
    }
}    

Insert image description here
4. int compareToIgnoreCase(String str) method: the same as compareTo, but ignores case comparison

public class Test {
    
    
    public static void main(String[] args) {
    
    
        String s = new String("abc");
        String s1 = new String("ac");
        String s2 = new String("ABc");
        String s3 = new String("abcde");
        System.out.println(s.compareToIgnoreCase(s1));//不同输出字符的差值为-1
        System.out.println(s.compareToIgnoreCase(s2));//输出字符相同为0
        System.out.println(s.compareToIgnoreCase(s3));//前几个字符相同,输出长度差值为-2
    }
}    

Insert image description here

3. String search

String search is also a very common operation in strings. The String class provides common search methods:

method Function
char charAt(int index) Returns the character at index position. If index is negative or out of bounds, an IndexOutOfBoundsException exception is thrown.
int indexOf(int ch) Returns the position where ch first appears, without returning -1
int indexOf(int ch, int fromIndex) Start from the fromIndex position to find the position where ch first appears. No -1 is returned.
int indexOf(String str) Returns the position where str first appears, without returning -1
int indexOf(String str, int fromIndex) Find the first occurrence of str starting from the fromIndex position, without returning -1
int lastIndexOf(int ch) Search from back to front, return to the position where ch first appears, if not return -1
int lastIndexOf(int ch, int fromIndex) Start searching from the fromIndex position, and search from back to front for the position where ch first appears. -1 is not returned.
:int lastIndexOf(String str) Search from back to front, return the position where str first appears, and do not return -1:
int lastIndexOf(String str, int fromIndex) Start searching from the fromIndex position, and search from back to front for the position where str first appears. No -1 is returned.
public class Test {
    
    
    public static void main(String[] args) {
    
    
        String s = "aaabbbcccaaabbbccc";
        System.out.println(s.charAt(3)); 
        System.out.println(s.indexOf('c'));
        System.out.println(s.indexOf('c', 10));
        System.out.println(s.indexOf("bbb"));
        System.out.println(s.indexOf("bbb", 10));
        System.out.println(s.lastIndexOf('c'));
        System.out.println(s.lastIndexOf('c', 10));
        System.out.println(s.lastIndexOf("bbb"));
        System.out.println(s.lastIndexOf("bbb", 10));
    }
}

Insert image description here

4. Conversion

1. Conversion of numerical values ​​and strings

public class Test {
    
    
    public static void main(String[] args) {
    
    
        String s1 = String.valueOf(1234);
        String s2 = String.valueOf(12.34);
        String s3 = String.valueOf(true);
        System.out.println(s1);
        System.out.println(s2);
        System.out.println(s3);
        System.out.println("=================================");
        // 字符串转数字
        // 注意:Integer、Double等是Java中的包装类型
        int data1 = Integer.parseInt("1234");
        double data2 = Double.parseDouble("12.34");
        System.out.println(data1);
        System.out.println(data2);
    }
}

Insert image description here
2. Case conversion

public class Test {
    
    
    public static void main(String[] args) {
    
    
        String s = "hello";
        String s1 = "HELLO";
        System.out.println(s.toUpperCase());//小写转大写
        System.out.println(s1.toLowerCase());//大写转小写
    }
}    

Insert image description here
These two functions only convert letters
3. String to array

public class Test {
    
    
    public static void main(String[] args) {
    
    
        String s = "hello";
        // 字符串转数组
        char[] ch = s.toCharArray();
        for (int i = 0; i < ch.length; i++) {
    
    
            System.out.print(ch[i]);
        }
        System.out.println();
        // 数组转字符串
        String s2 = new String(ch);
        System.out.println(s2);
    }
}

Insert image description here
4.Formatting

public class Test {
    
    
    public static void main(String[] args) {
    
    
        String s = String.format("%d-%d-%d", 2019, 9,14);
        System.out.println(s);
    }
}

Insert image description here

5. String replacement

Use a specified new string to replace existing string data. The available methods are as follows:

method Function
String replaceAll(String regex, String replacement) Replace all specified content
String replaceFirst(String regex, String replacement) Replace the received content
public class Test {
    
    
    public static void main(String[] args) {
    
    
        String s = "hellohello";
        System.out.println(s.replaceAll("l", "z"));
        System.out.println(s.replaceFirst("l", "z"));
    }
}    

Insert image description here
Note: Since string is an immutable object, replacement does not modify the current string, but generates a new string

6. String splitting

A complete string can be divided into several substrings according to the specified delimiter
The method is as follows:

method Function
String[] split(String regex) Split all strings
String[] split(String regex, int limit) Split the string into limit groups in the specified format
public class Test {
    
    
    public static void main(String[] args) {
    
    
        String str = "hello word is you";
        String[] s = str.split(" ");//按照空格拆分
        for (int i = 0; i < s.length; i++) {
    
    
            System.out.println(s[i]);
        }
    }
}

Insert image description here

public class Test {
    
    
    public static void main(String[] args) {
    
    
        String str = "hello word is you";
        String[] s = str.split(" ",2);//按照空格拆分成两份
        for (int i = 0; i < s.length; i++) {
    
    
            System.out.println(s[i]);
        }
    }
}    

Insert image description here
Splitting is a very common operation. It must be mastered. In addition, some special characters may not be segmented correctly as delimiters and need to be escaped.
Notes: Multiple splits: 3. If there are multiple delimiters in a string, you can use "|" as a hyphen 2. And if "", then it must be written as "\\"
1. The characters "|", "*", "+" must be added with escape characters, preceded by "\"


public class Test {
    
    
    public static void main(String[] args) {
    
    
        String str = "name=zhagnsan&age=10";
        String[] s = str.split("&");
        for (String ss:s) {
    
    
            String[] ret = ss.split("=");
            for (String sss:ret) {
    
    
                System.out.println(sss);
            }
        }
    }
}

Insert image description here

7. String interception

Extract part of the content from a complete string
The method is as follows:

method Function
String substring(int beginIndex) Truncate from the specified index to the end
String substring(int beginIndex, int endIndex) Cut out part of the content
public class Test {
    
    
    public static void main(String[] args) {
    
    
        String str = "helloword";
        System.out.println(str.substring(5));
        System.out.println(str.substring(0, 5));
    }
}    

Insert image description here
Notes:
1. The index starts from 0
2. Pay attention to the front closed and back open intervals Writing method, substring(0,5) means the characters containing the 0 subscript, but not the characters containing the 5 subscript

8. Other operating methods

method Function
String trim() Remove the left and right spaces in the string and keep the middle spaces
String toUpperCase() Convert string to uppercase
String toLowerCase() Convert string to lowercase
public class Test {
    
    
    public static void main(String[] args) {
    
    
        String str = " hello word ";
        System.out.println(str.trim());
    }
}    

Insert image description here
trim will remove whitespace characters (spaces, newlines, tabs, etc.) at the beginning and end of the string

9. Immutability of strings

String is an immutable object. The content in the string cannot be changed. The string cannot be modified because:
1. The String class is immutable at design time. This has been stated in the String class implementation description.
Insert image description here
In the String class The characters are actually stored in the internally maintained value character array, as can be seen from the above figure:
1. The String class is modified by final, indicating that the class cannot be inherited
2. Value is modified by final, indicating that the value of value itself cannot be changed, that is, it cannot reference other character arrays, but the content in its reference space can be modified
2. All possible modifications involved The operation of the string content is to create a new object, and what is changed is the new object
The string is immutable because the array storing the characters inside is modified by final and therefore cannot be changed.
This statement is wrong, not because the String class itself or its internal value is modified by final and cannot be modified.
The final modified class indicates that the class does not want to be inherited, and the final modified reference type indicates that the reference variable cannot refer to other objects, but the content in the reference object can be modified

10. String modification

Note: Try to avoid directly modifying String type objects, because the String class cannot be modified, and all modifications will create new objects, which is very inefficient

3. StringBuilder and StringBuffer

Due to the unchangeable nature of String, in order to facilitate the modification of strings, Java provides StringBuilder and StringBuffer classes. Most of the functions of these two classes are the same

method Function
StringBuff append(String str) Append at the end, equivalent to += of String, you can append: boolean, char, char[], double, float, int, long, Object, String, StringBuff variables
char charAt(int index) Get the character at index position
int length() Get the length of a string
int capacity() Get the total size of the underlying storage string space
void ensureCapacity(int mininmumCapacity) Expansion
void setCharAt(int index,char ch) Set the character at index position to ch
int indexOf(String str) Returns the position of the first occurrence of str
int indexOf(String str, int fromIndex) Find the first occurrence of str starting from the fromIndex position
int lastIndexOf(String str) Returns the position where str occurred last time
int lastIndexOf(String str,int fromIndex) Find the last occurrence of str starting from the fromIndex position.
StringBuff insert(int offset, String str) Insert at offset position: eight base class types & String type & Object type data
StringBuffer deleteCharAt(int index) Delete characters at index position
StringBuffer delete(int start, int end) Delete characters in the range [start, end)
StringBuffer replace(int start, int end, String str) Replace the characters at [start, end) positions with str
String substring(int start) The characters from start to the end are returned as String
String substring(int start,int end) Return characters in the range [start, end) as String
StringBuffer reverse() Reverse a string
String toString() Return all characters as String

The biggest difference between String and StringBuilder is thatString content cannot be modified, but StringBuilder content can be modified. If strings are frequently modified, consider using StringBuilder
Note: String and StringBuilder classes cannot be converted directly. If you want to convert each other, you can adopt the following principles:
1. String becomes StringBuilder: Use the construction method or append() method of StringBuilder
2. StringBuilder becomes StringBuilder For String: Call toString() method

The difference between String, StringBuffer and StringBuilder
1. The content of String cannot be modified, but the content of StringBuffer and StringBuilder can be modified.
2.StringBuffer and Most of the functions of StringBuilder are similar
3. StringBuffer uses synchronous processing and is a thread-safe operation; StringBuilder does not use synchronous processing and is a thread-unsafe operation

Guess you like

Origin blog.csdn.net/2301_78373304/article/details/134570817