[Java] The difference between split and subString in the String class of Java basics

        The String class in Java contains many methods. Today, let’s briefly summarize the interception methods of String strings. There are two interception methods for strings ( split and subString , but each has overloads):

String interception method
Method name description
String[] split(String regex) Split this string according to the match of the given regular expression (returns an array)
String[] split(String regex,int limit) Split this string based on matching the given regular expression (returns an array)
String[] subString(int beginIndex) Returns a new string, which is a substring of this string (returns a string)
String[] subString(int beginIndex, int endIndex) Returns a new string, which is a substring of this string (returns a string)

Split parameter description:

        regex: regular expression separator

        limit: the number of divided copies

SubString parameter description:

        beginIndex: start index (inclusive), index starts from 0

        endIndex: end index (not included)

Split instance:

package com.james;

public class StringTest {
    public static void main(String[] args) {
        String s="welcome-to-china";
        String[] strings=s.split("-");
        String[] strings1=s.split("-",2);
        //遍历根据“-”截取后的结果
        for (int i = 0; i < strings.length; i++) {
            System.out.println(strings[i]);
        }
        System.out.println("============");
        //遍历根据“-”截取后的结果,限制条件(截取两份)
        for (int i = 0; i < strings1.length; i++) {
            System.out.println(strings1[i]);
        }
    }
}

The print result is as follows:

                                                      

Examples of subString():

package om.james;
public class subStringTest {
    public static void main(String[] args) {
        String s="welcome to china";
        //从索引为2开始截取字符串
        String s1=s.substring(2);
        //从索引为2开始截取字符串,终止索引为5
        String s2=s.substring(2,5);
        System.out.println(s1);
        System.out.println(s2);
    }
}

Print result:

                            

Guess you like

Origin blog.csdn.net/weixin_43267344/article/details/107898010