[Take you step by step to learn JavaSE] String class (Part 2)

Preface

In the previous article, we have learned some knowledge about the String class, let’s continue learning next!

1. String search

String search is also a very common operation in strings. The String class provides common search methods.
Insert image description here
Insert image description here

2. String conversion

2.1 Numeric and string conversion

static String valueof() Convert numeric value to string
Integer.parseInt() String integer
Double.parseDouble() Convert string to floating point type

class Student{
    
    
    String name;
    int age;
    public Student(String name,int age){
    
    
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
    
    
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
public class Test {
    
    
    public static void main(String[] args) {
    
    
        String s1 = String.valueOf(123);
        String s2 = String.valueOf(12.3);
        String s3 = String.valueOf(true);
        String s4 = String.valueOf(new Student("ahdiauhd",23));

        System.out.println(s1);
        System.out.println(s2);
        System.out.println(s3);
        System.out.println(s4);
        System.out.println("===========================");

        int data1 = Integer.parseInt("1234");
        double data2 = Double.parseDouble("12.5");
        System.out.println(data1);
        System.out.println(data2);
    }
}

Insert image description here

2.2 Case conversion

String toUpperCase() Convert to uppercase
String toLowerCase() Convert to lowercase
These two functions only convert letters.

public static void main(String[] args) {
    
    
        String s1 = "Hello";
        String s2 = "HADSDKJA";

        //小写转大写
        System.out.println(s1.toUpperCase());
        //大写转小写
        System.out.println(s2.toLowerCase());
    }

Insert image description here

2.3 Conversion of strings and arrays

char[ ] toCharArray() string to array
new String (array reference) array to string

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

Insert image description here

2.4 Formatting

static String format( );

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

Insert image description here

3. String replacement

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

Insert image description here

public static void main(String[] args) {
    
    
        String s = "Hello World!";
        System.out.println(s.replace("l","a"));
        System.out.println(s.replaceFirst("l","k"));

    }

Insert image description here
Note: Since strings are immutable objects, replacement does not modify the current string, but generates a new string.

4. String splitting

A complete string can be divided into several substrings according to the specified delimiter.

Insert image description here

4.1 Split processing

public static void main(String[] args) {
    
    
        String s1 = "Hello World! Hahaha asjkd";
        String[] arr = s1.split(" ");//按空格拆分
        for (String s:arr) {
    
    
            System.out.println(s);
        }
    }

Insert image description here

4.2 Partial split

public static void main(String[] args) {
    
    
        String s1 = "Hello World! Hahaha asjkd";
        String[] arr = s1.split(" ",2);
        for (String s:arr) {
    
    
            System.out.println(s);
        }
    }

Insert image description here

4.3 Split IP address

public static void main(String[] args) {
    
    
        String str = "188.166.1.1" ;
        String[] arr = str.split("\\.") ;
        for(String s: arr) {
    
    
            System.out.println(s);
        }
    }

Insert image description here

5. String interception

Insert image description here

public static void main(String[] args) {
    
    
        String s = "Hello World!";
        System.out.println(s.substring(0));
        System.out.println(s.substring(0,5));
    }

Insert image description here
1. Index starts from 0.
2. Pay attention to the writing method of the interval that is closed at the beginning and open at the end. substring(0, 5) means the character containing the subscript 0, but not the subscript 5.

6. Other methods

6.1 String trim()

Method: String trim()

Function: Remove the left and right spaces in the string and keep the middle space.

public static void main(String[] args) {
    
    
        String s = "         Hello World     ";
        System.out.println("[" +s+"]");
        System.out.println("[" +s.trim()+"]");
    }

Insert image description here

6.2 boolean isEmpty()

isEmpty() method is used to determine whether a string is empty

public static void main(String[] args) {
    
    
        String s = "     ";
        System.out.println(s.isEmpty());
    }

Insert image description here

6.3 int length()

Used to find the length of a string

public static void main(String[] args) {
    
    
        String s = "MoyuWangPangdudu";
        System.out.println(s.length());
    }

Insert image description here

6.4 Determine the beginning and end of a string

boolean startsWith(String prefix)
boolean endWith(String sufix) determines whether the string ends with a certain string

public static void main(String[] args) {
    
    
        String s = "MoyuWangPangdudu";
        System.out.println(s.startsWith("Mo"));
        System.out.println(s.endsWith("dudu"));
    }

Insert image description here

6.5 boolean contains(String str)

Determine whether a string contains a certain string

public static void main(String[] args) {
    
    
        String s = "MoyuWangPangdudu";
        System.out.println(s.contains("Wang"));
    }

Insert image description here

七、StringBuilder&&StirngBuffer

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. Here are some commonly used methods of StringBuilder.

Insert image description here

public static void main(String[] args) {
    
    
        StringBuilder sb1 = new StringBuilder("Hello");
        StringBuilder sb2 = sb1;

        //追加:即尾插->字符、字符串、整型数字
        sb1.append("   ");//Hello
        sb1.append("World!");//Hello   World!
        sb1.append(123);//Hello   World!123
        System.out.println(sb1);


        System.out.println(sb1 == sb2);//true

        System.out.println(sb1.charAt(0)); // 获取0号位上的字符 H

        System.out.println(sb1.length());// 获取字符串的有效长度17

        System.out.println(sb1.capacity());// 获取底层数组的总大小

        sb1.setCharAt(0, 'h'); // 设置任意位置的字符 hello   World!123

        sb1.insert(0,"Hello World!!");// Hello world!!Hello   World!123
        System.out.println(sb1);
        System.out.println(sb1.indexOf("Hello")); // 获取Hello第一次出现的位置
        System.out.println(sb1.lastIndexOf("hello"));// 获取hello最后一次出现的位置

        sb1.deleteCharAt(0); // 删除首字符
        System.out.println(sb1);
        sb1.delete(0,5);// 删除[0, 5)范围内的字符
        System.out.println(sb1);

        String str1 = sb1.substring(0,5);// 截取[0, 5)区间中的字符以String的方式返回
        System.out.println(str1);

        sb1.reverse();//字符串逆转
        str1 = sb1.toString(); // 将StringBuffer以String的方式返回
        System.out.println(str1);
    }

Insert image description here

The biggest difference between String and StringBuilder is that the content of String cannot be modified, while the content of StringBuilder can be modified . Consider using StringBuilder if strings are frequently modified.

Notice:

The String and StringBuilder classes cannot be converted directly. If you want to convert each other, you can use the following principles:

String becomes StringBuilder:
Use the constructor of StringBuilder (StringBuilder(String str) to construct a string generator and initialize it to the specified string content) or the append() method

StringBuilder becomes String:
Call the toString() method rewritten by StringBuilder

7.2 Differences between String, StringBuffer and StringBuilder

  1. The contents of String cannot be modified, but the contents of StringBuffer and StringBuilder can be modified.
  2. Most functions of StringBuffer and 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/weixin_61341342/article/details/126901116