Technology Sharing

Java - String Class

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

1. What is the String class?

I think you have come into contact with strings when learning C language, but in C language, strings can only be represented by
Character array char[10] str = "hello"; or character pointer char *str = "hello";No dedicated String class is provided. In object-oriented Java, the String class and its operations are specifically provided, which makes it more convenient for us programmers to use.

Immutability of Strings

The content of the string cannot be changed.
insert image description here

  • The characters in the String class actually maintain a character array called value.
  • The String class is modified by final, which means that final cannot be inherited.
  • final modifies value, indicating that value cannot reference other arrays, but the contents of the array can still be changed!

In String, all operations that may modify the string content create a new object and change the new object.
For example, in the substring:
insert image description here
Some people say: Strings are immutable because the array that holds the characters inside them is finalized and therefore cannot be changed.

  • This statement is incorrectFirst, final modifies String to indicate that the String class is the final class, which cannot be modified or inherited. Final modifies the reference type to indicate that the reference variable cannot reference other objects, but the content of the referenced object can still be modified.
  public static void main(String[] args) {
        final char[] arr = {'h','e','l','l','o'};
        arr[0] = 'H';
        System.out.println(String.valueOf(arr));//Hello
        // arr = new char[]{'h','o'};Error

    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

2. Basic usage of String class

1 String construction

String is a reference data type and does not store the string itself.

public class Test {
    public static void main(String[] args) {
        //1.直接赋值
        String s1 = "first";
        //2.new 对象
        String s2 = new String("second");
        //3. 创建字符数组
        char[] arr = {'t','h','i','r','d'};
        String s3 = new String(arr);
        
        System.out.println(s1);
        System.out.println(s2);
        System.out.println(s3);
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

insert image description here

Notice:
String s1 = “first”;
The Java Virtual Machine (JVM) will first check whether the string "first" already exists in the string constant pool. If it does, it will directly return the reference of the string in the constant pool; if it does not exist, it will add the string to the constant pool and return its reference in the constant pool.

2 Comparison of String objects

  1. == compares whether they are the same reference
     //s1 s2 分别是new 一个新的字符串"hello"
    String s1 = new String("hello");
	String s2 = new String("hello");
	String s3 = "Hello";
	String s4 = s1;

	System.out.println(s1 == s2);//false
 	System.out.println(s1 == s4);//true
	System.out.println(s1 == s3);//false
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  1. equals() is used to determine whether two strings are equal. If they are equal, it returns true, otherwise false
      
        //因为Object类中的equals()方法是==实现的,完成不了String类的需求,
        //所以String对equals()实现了重写

        String s1 = new String("hello");
        String s2 = new String("hello");
        String s3 = "Hello";
        String s4 = s1;

        System.out.println(s1.equals(s2));//true
       	System.out.println(s1.equals(s4));//true
        System.out.println(s1.equals(s3));//false
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

insert image description here
3. compareTo() compares in lexicographical order, and the return value is int

        /*
        * 比较的方式有一下两种:
        * 1.先一个一个字符相比较,如果出现不同的字符,则返回差值
        * 2.如果前x个字符相等,则返回两个字符串的长度差值
        * */

        String s1 = new String("abc");
        String s2 = new String("abcdef");
        String s3 = new String("abd");
        String s4 = new String("abc");
        
        System.out.println(s1.compareTo(s2));//-3 (3-6)
        System.out.println(s1.compareTo(s3));//-1
        System.out.println(s1.compareTo(s4));//0
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  1. compareToIgnoreCase() Same as compareTo, but ignores case

        String s1 = new String("Abc");
        String s2 = new String("aBcdef");
        String s3 = new String("aBd");
        String s4 = new String("ABc");

        System.out.println(s1.compareToIgnoreCase(s2));//-3 (3-6)
        System.out.println(s1.compareToIgnoreCase(s3));//-1
        System.out.println(s1.compareToIgnoreCase(s4));//0

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

3. String search

methodFunction
char charAt(int index)Returns the character at index. If index is negative or out of bounds, throws IndexOutOfBoundsException.
int indexOf(int ch)Returns the position of the first occurrence of ch, or -1 if not found
int indexOf(int ch, intfromIndex)Find the first occurrence of ch starting from fromIndex, and return -1 if yes.
int indexOf(String str)Returns the position of the first occurrence of str, or -1 if not found
int indexOf(String str, intfromIndex)Find the first occurrence of str starting from fromIndex. If not found, return -1.
int lastIndexOf(int ch)Search from back to front, return the first occurrence of ch, if not return -1
int lastIndexOf(int ch, intfromIndex)Start from fromIndex and search for the first occurrence of ch from the back to the front. If not found, return -1.
int lastIndexOf(String str)Search from back to front, return the first occurrence of str, if not return -1
int lastIndexOf(String str, intfromIndex)Start from fromIndex and search for the first occurrence of str from back to front. If not found, return -1.

 public static void main(String[] args) {
 
        String s = "Hello, how are you today?";
        System.out.println(s.charAt(2)); //l
        System.out.println(s.indexOf('H')); //0
        System.out.println(s.indexOf('l',2)); //从第二个开始找 2
        System.out.println(s.indexOf("are")); //11
        System.out.println(s.indexOf("are",12)); // 未找到-1
        System.out.println(s.lastIndexOf('l')); //从后往前数 3
        System.out.println(s.lastIndexOf('l',3));// 从第三个往后数 3
        System.out.println(s.lastIndexOf("how"));// 7
        System.out.println(s.lastIndexOf("how",6));// 未找到 -1

    }

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

4. Conversion

1. Conversion between numbers and strings

		String s1 = String.valueOf(1234);
        String s2 = String.valueOf(12.34);
        String s3 = String.valueOf(true);
        String s4 = String.valueOf(new Student("Hanmeimei", 18));
        System.out.println(s1);//1234 String
        System.out.println(s2);//12.34 String
        System.out.println(s3);//true String
        System.out.println(s4);//Student@1b6d3586
        System.out.println("=================================");
        int data1 = Integer.parseInt("1234");
        double data2 = Double.parseDouble("12.34");
        System.out.println(data1);//1234
        System.out.println(data2);//12.34
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

2. Case conversion

 		String s1 = "hello";
        String s2 = "HELLO";
        System.out.println(s1.toUpperCase());//HELLO
        System.out.println(s1.toLowerCase());//hello
  • 1
  • 2
  • 3
  • 4

3. Convert string to character array and character array to string

 		//字符串转字符数组
        String s = "What can I say!";
        char[] arr = s.toCharArray();
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]);
        }
        System.out.println();
        //字符数组转字符串
        String s1 = new String(arr);
        System.out.println(s1);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

4. Formatting

		//格式化
        String s = String.format("%d/%02d/%d",2024,07,10);
        System.out.println(s);//2024/07/10
  • 1
  • 2
  • 3

5. String Replacement

methodFunction
String replaceAll(String regex, String replacement)Replace all specified contents
String replaceFirst(String regex, String replacement)Replace the first content
		String s = "What can I say say!";
        System.out.println(s.replaceAll("say","look"));
        System.out.println(s.replaceFirst("say","SAY"));

        //What can I look look!
        //What can I SAY say!
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

6. String Splitting

methodFunction
String[] split(String regex)Split all strings
String[] split(String regex, int limit)Split the string into limit groups in the specified format
 		//字符串拆分
        String s = "字 符 串 拆 分";
        String[] str = s.split(" ");
        for(String i : str) {
            System.out.print(i+"|");
        }
        System.out.println();
        String[] str2 = s.split(" ",2);
        for(String i : str2) {
            System.out.println(i);
        }
        
        /*
        * 输出:
        字|符|串|拆|分|
        字
        符 串 拆 分
        * */
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
       /*
       *拆分是特别常用的操作:
       * 一定要重点掌握
       *另外有些特殊字符(通配符)作为分割符可能无法正确切分, 需要加上转义.
       * */
       String s2 = "192.168.1.16" ;
       String[] result = s2.split("\.") ;
       for(String i: result) {
           System.out.println(i);
       }
       System.out.println("\");
       //为了匹配字面上的点号,你需要使用反斜杠()来转义它,
       // 但在Java字符串中,反斜杠本身也是一个转义字符,
       // 所以你需要使用双反斜杠(\)来表示一个字面量上的反斜杠。
       
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

7. String interception

	 //字符串截取
        String s = "What can I say!";
        System.out.println(s.substring(6));//an I say!
        System.out.println(s.substring(0,3));//What
  • 1
  • 2
  • 3
  • 4

8. Remove leading and trailing spaces from a string

	 String s = "   yy ds       ";
        System.out.println(s.trim());//yy ds
  • 1
  • 2

10. String modification

The String class cannot be modified, and all modifications will create new objects, which is inefficient.
insert image description here
It only takes 341ms for 10,000 calls. If you want to modify it, it is recommended to use StringBuffer or StringBuilder.

StringBuffer and StringBuilder

Because String is immutable, Java provides StringBuilder and StringBuffer classes to facilitate string modification. Most of the methods of these two classes are the same.
If you are interested, you can clickOnline documentation

insert image description here

After 1ms using StringBuffer.
insert image description here
Note: String and StringBuilder classes cannot be converted directly. If you want to convert between them, you can use the following principles:

  • String becomes StringBuilder: Use the StringBuilder constructor or append() method
  • StringBuilder becomes String: call toString() method

The difference between String, StringBuffer and StringBuilder

  • The content of String cannot be modified, but the content of StringBuffer and StringBuilder can be modified.
  • StringBuffer uses synchronization and is a thread-safe operation; StringBuilder does not use synchronization and is a thread-unsafe operation.
    do

The so-called thread safety is like multiple people going to the toilet. At this time, there is only one toilet. You go in first, close the door, and come out after you are done. During this period, you have exclusive use of this toilet and no one else can come in. Complete the current task first, monopolize the resources, and release the occupied resources after you are done.