Java String split() method detailed tutorial

The split() method of the Java String class splits the string according to the given regular expression and returns a character array.

1. Internal implementation


public String[] split(String regex, int limit) {
    
      
        /* 如果正则表达式是一个快速路径 
         (1)one-char String 且此字符不是其中之一 
            正则表达式的元字符“.$|()[{^?*+\\”,或 
         (2)双字符字符串,第一个字符是反斜杠和 
            第二个不是 ascii 数字或 ascii 字母
         */  
        char ch = 0;  
        if (((regex.value.length == 1 &&  
             ".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1) ||  
             (regex.length() == 2 &&  
              regex.charAt(0) == '\\' &&  
              (((ch = regex.charAt(1))-'0')|('9'-ch)) < 0 &&  
              ((ch-'a')|('z'-ch)) < 0 &&  
              ((ch-'A')|('Z'-ch)) < 0)) &&  
            (ch < Character.MIN_HIGH_SURROGATE ||  
             ch > Character.MAX_LOW_SURROGATE))  
        {
    
      
            int off = 0;  
            int next = 0;  
            boolean limited = limit > 0;  
            ArrayList<String> list = new ArrayList<>();  
            while ((next = indexOf(ch, off)) != -1) {
    
      
                if (!limited || list.size() < limit - 1) {
    
      
                    list.add(substring(off, next));  
                    off = next + 1;  
                } else {
    
        // 最后一个
                    //assert (list.size() == limit - 1);  
                    list.add(substring(off, value.length));  
                    off = value.length;  
                    break;  
                }  
            }  
            // 如果未找到匹配项,则返回此
            if (off == 0)  
                return new String[]{
    
    this};  
  
            //添加剩余部分  
            if (!limited || list.size() < limit)  
                list.add(substring(off, value.length));  
  
            //构建结果 
            int resultSize = list.size();  
            if (limit == 0)  
                while (resultSize > 0 && list.get(resultSize - 1).length() == 0)  
                    resultSize--;  
            String[] result = new String[resultSize];  
            return list.subList(0, resultSize).toArray(result);  
        }  
        return Pattern.compile(regex).split(this, limit);  
    }

2. Grammar

The split() method of the Java String class has two syntaxes.

public String split(String regex)  
 
public String split(String regex, int limit)

3. Parameters

regex: The regular expression to apply to the string.
limit: The limit on the number of strings in the array. If zero, returns all strings that match the regular expression.

4. Return value

array of strings

5. Throw an exception

If the pattern of the regular expression is invalid, a PatternSyntaxException is thrown.

6. Example of Java String split() method

The following example returns the total number of words in a string excluding spaces. It also includes special characters.


public class SplitExample{
    
      
public static void main(String args[]){
    
      
String s1="java string split method by javatpoint";  
String[] words=s1.split("\\s");//根据空格分割字符串
//使用 java foreach 循环打印字符串数组的元素
for(String w:words){
    
      
System.out.println(w);  
}  
}}

java
string
split
method
by
javatpoint

7. Java String split() method with regular expression and length example

public class SplitExample2{
    
      
public static void main(String args[]){
    
      
String s1="welcome to split world";  
System.out.println("returning words:");  
for(String w:s1.split("\\s",0)){
    
      
System.out.println(w);  
}  
System.out.println("returning words:");  
for(String w:s1.split("\\s",1)){
    
      
System.out.println(w);  
}  
System.out.println("returning words:");  
for(String w:s1.split("\\s",2)){
    
      
System.out.println(w);  
}  
  
}}

returning words:
welcome 
to 
split 
world
returning words:
welcome to split world
returning words:
welcome 
to split world

8. Java String split() method, regular expression and length example 2

Here, we pass the split limit as the second argument to the function. This limits the number of split strings.


public class SplitExample3 {
    
      
    public static void main(String[] args) {
    
      
        String str = "Javatpointtt";  
        System.out.println("Returning words:");  
        String[] arr = str.split("t", 0);  
        for (String w : arr) {
    
      
            System.out.println(w);  
        }  
        System.out.println("Split array length: "+arr.length);  
    }  
}

Returning words:
Java
poin

Split array length: 2

Guess you like

Origin blog.csdn.net/weixin_43025151/article/details/130812048