Java is really not difficult to String class

Posted by Theophilus on Tue, 11 Jan 2022 10:53:40 +0100

String

String class:
Represents a string. It provides string processing methods commonly used in development, such as finding the length of a string, intercepting a string, replacing a string, etc. the character string is a constant, and its value cannot be modified after it is created.

First, let's check the official document to see what methods the official has set for the String class:
String also belongs to Java Lang package, so you don't need to import it. Part of it is shown here. For all the contents, please refer to: https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html

Several common methods:

  • charAt(int index):
    Enter the character subscript, intercept the character, and the return value is char type:
        String str = "hello world";
        char a = str.charAt(0);
        System.out.println(a);
//Output: h
  • compareTo(String anotherString):
    Compare two strings to match characters with different subscript corresponding characters first, return the difference of ASCII code, do not ignore case, and return String type:
String str = "hello world";
int a = str.compareTo("Aello world");
System.out.println(a);
//h and A ratio, output 39
  • compareToIgnoreCase(String str):
    Compare two strings in dictionary order, ignore case, and return String type:
String str = "hello world";
int a = str.compareToIgnoreCase("Aello world");
System.out.println(a);
//h and A ratio, output 7
  • concat(String str):
    Splice string:
String str = "hello world";
String a = str.concat("abc");
System.out.println(a);
//Output: hello worldabc
  • contains(CharSequence s):
    Check whether the string contains a value and return the Boolean value:
String str = "hello world";
boolean a = str.contains("e"); //Pass in the value to be judged
 System.out.println(a)
 //Output: true

boolean a = str.contains("a");  //Judgement a
System.out.println(a);
//Output false
  • endsWith(String suffix):
    Judge whether to return a Boolean value at the specified end (you can judge by the user's mailbox suffix):
String str = "1234567489@qq.com";
boolean a = str.endsWith("@qq.com");  //Content to be judged
System.out.println(a);
//Output: true
  • startsWith(String prefix):
    The judgment string starts with the specified prefix: (URL judgment) returns the Boolean value:
String str = "www.baidu.com";
boolean a = str.startsWith("www");
System.out.println(a);
//Output: true
  • equals(Object anObject):
    Compare whether the string is equal to the specified string, case sensitive, and return a Boolean value:
String str = "www.baidu.com";
boolean a = str.equals("Www.baidu.com");  //Change the first w to capital W
System.out.println(a);
//Output: false
//If both are the same, output true
  • equalsIgnoreCase(String anotherString):
    Compare whether the string is equal to the specified string, case insensitive, and return a Boolean value:
String str = "www.baidu.com";
boolean a = str.equalsIgnoreCase("Www.Baidu.com");  //Change the first w to capital W
System.out.println(a);
//After case insensitive, even if one or more characters are changed to uppercase, the judgment will not be affected
//Output true
  • indexOf(String str):
    Returns the index of the specified value found for the first time in the string, and returns the int type:
String str = "www.baidu.com";
int a = str.indexOf("a");  //Judgement a
System.out.println(a);
//Output: 5
  • lastIndexOf(String str):
    Returns the index of the last time the specified value is found in the string, and returns the int type:
String str = "www.baidu.com";
int a = str.indexOf("a");  //Judge a, because this string has only one a, so it is still 5
System.out.println(a);
//Output: 5
  • length():
    Return string length, int type:
String str = "www.baidu.com";
int a = str.length();
System.out.println(a);
//Output: 13
  • toLowerCase():
    Convert the String to lowercase letters. If it is lowercase, it will not change and return the String type:
String str = "www.BAIDU.com";
String a = str.toLowerCase();
System.out.println(a);
//Output: www.baidu.com com
  • toUpperCase():
    Convert string to uppercase:
String str = "WWW.BAIDU.COM";
String a = str.toLowerCase();
System.out.println(a);
//Output:
  • trim():
    Remove whitespace at both ends of the string:
String str = "       www.baidu.com     ";   //Output multiple spaces at the front and back ends
String a = str.trim();
System.out.println(a);
//Output: www.baidu.com com
  • String substring(int beginIndex,int endIndex):
    Intercepted string (index contains beginIndex but not endIndex):
String str = "www.baidu.com";
String a = str.substring(0,6);  //Interception starts with subscript 0 and ends with subscript 6 (excluding characters with subscript 6)
System.out.println(a);
//Output: www.ba

There are many other methods of String. We won't list them one by one here. You can refer to the official website documents for use

However, the length of a String object is fixed, its content cannot be changed, and new characters cannot be attached to the String object. In fact, this can not meet the business requirements sometimes. There are always times when it is necessary to change the String, so Java gives two variable strings of String buffers: StringBuffer and StringBuilder.

StringBuffer and StringBuilder:

First, let's look at the official introduction:

Simply put, StringBuffer is a variable character sequence. The length and content of the column can be changed by calling some methods. Some StringBuffer methods are as follows. For details, please refer to: https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/StringBuffer.html

The official method of append is overloaded to meet the needs of different business logic.
Because StringBuffer is a class, you need to create a class to use it:

public class StringBuffertest {
    public static void main(String[] args) {

        String str = "hello world";
        StringBuffer s = new StringBuffer(str);  //Create the StringBuffer class, which is the same as the normal class creation method
        s.append("hello world");    //Use the append method of StringBuffer
        System.out.println(s);
    }
}
//Output: Hello World Hello World
//This completes the modification of the string

The usage of StringBuilder is the same:

String str = "hello world";
StringBuilder s = new StringBuilder(str);

What is the difference between String and StringBuilder and StringBuffer?

  1. Variability: String is an immutable character sequence, and Builder and Buffer are variable character sequences
  2. Security: String is thread safe, StringBuilder is thread unsafe, and StringBuffer is thread safe. StringBuffer is more efficient than StringBuffer. Because String is immutable, in general, the efficiency is the lowest.
  3. Usage scenario: if there is basically no need to change the String after it is created, use String type. If there are many changes, use StringBuilder. If thread safety is required, use StringBuffer.

Benefits of StringBuffer and StringBuilder classes:

  • Objects can be modified multiple times without generating new unused objects

String class summary:

What are the characteristics of String

  1. Invariance: String is a read-only String. It is a typical immutable object. Any operation on it is actually a creation
    Create a new object and point the reference to it. The main function of invariant mode is when an object needs to be shared and shared by multiple threads
    Data consistency can be guaranteed during frequent access.
  2. Constant pool Optimization: after the String object is created, it will be cached in the String constant pool. If the same object is created next time,
    The cached reference is returned directly.
  3. Final: use final to define the String class, which means that the String class cannot be inherited, which improves the security of the system.

Small extension: what is a string constant pool?

  • The string constant pool is located in heap memory and is specially used to store string constants, which can improve memory utilization and avoid opening up multiple blocks of space to store the same string. When creating a string, the JVM will first check the string constant pool. If the string already exists in the pool, it will return its reference. If it does not exist, it will instantiate a string and put it in the pool, And returns its reference.

The difference between character constant (char) and String constant (String):

  1. Formally: the character constant is a character string caused by single quotation marks, and the constant is several characters caused by double quotation marks
  2. Meaning: the character constant is equivalent to an integer value (ASCII value) and can participate in expression operation. The string constant represents an address value (where the string is stored in memory)
  3. Memory size: character constants only occupy one byte, and string constants occupy several bytes (at least one character end flag)

Special attention:
We know that the array also has length(), which is used to judge the length of the array:

int [] a = {1,2,3,4,5};
system.out.println(a.length);
//Output: 5

But be careful:

length() in the array is an attribute and length() in the String is a method!!
length() in the array is an attribute and length() in the String is a method!!
length() in the array is an attribute and length() in the String is a method!!

Topics: Java Back-end