Split string

String.split() split string

Split() method of lang package String class

public String[] split(String regex)
public String[] split(String regex,int limit)
//limit 参数控制模式应用的次数,因此影响所得数组的长度
拆分示例:

public class SplitDemo {
    
    
    public static void main(String[] args) {
    
    
        String Str="Harry James Potter";
        String[] StrArray=Str.split("\\s");//"\\s"表示空格
        //也可以来" "来进行拆分  String[] StrArray=Str.split(" ");
        for(String str:StrArray){
    
    
            System.out.println(str);
        }
}

Operation result
Harry
James
Potter

StringTokenizer class split string

StringTokenizer class under the util package

Splitting principle
StringTokenizer splits the string by generating a StringTokenizer object, and then using the properties of the object to process the string splitting.

StringTokenizer public (STR String, String the delim, the returnDelims Boolean)
public StringTokenizer (STR String, String the delim)
public StringTokenizer (String STR)
// STR: string to be parsed delim: Separator returnDelims: whether the delimiter is returned as tokens
removed Example of points:

import java.util.StringTokenizer;
public class StringTokenDemo {
    
    
    public static void main(String[] args) {
    
    
        String Str="Harry James Potter";
        StringTokenizer strToken=new StringTokenizer(Str);
        //当有拆分的子字符串时,输出这个字符串
        while(strToken.hasMoreTokens()){
    
    
            System.out.println(strToken.nextToken());
        }
    }
}

Operation result
Harry
James
Potter

Guess you like

Origin blog.csdn.net/qq_45783660/article/details/114632058