@
目錄
例如我要從一行學生信息中分割出學號、姓名、年齡、學歷等等
主要使用split方法,split方法在API中定義如下:
public String[] split(String regex)根據給定正則表達式的匹配拆分此字符串。
該方法的作用就像是使用給定的表達式和限制參數 0 來調用兩參數 split 方法。因此,所得數組中不包括結尾空字符串。
例如,字符串 "boo:and:foo" 使用這些表達式可生成以下結果:
- Regex 結果
-
{ "boo", "and", "foo" }
o { "b", "", ":and:f" }
參數:
regex - 定界正則表達式
返回:
字符串數組,它是根據給定正則表達式的匹配拆分此字符串確定的
拋出:
PatternSyntaxException - 如果正則表達式的語法無效
從以下版本開始:
1.4
另請參見:
Pattern
簡而言之,這個方法就是將這行數據比如使用空格隔開的,就按照空格來分割數據
需要分割的字符串.split("如果是空格分隔的字符串這里就是一個空格");
- 例子1:11242 張三 12 高中
用String.split(String regex");
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
String[] a=in.nextLine().split(" ");
int num=Integer.valueOf(a[0]);
String name=a[1];
int age=Integer.valueOf(a[2]);
String xueli=a[3];
System.out.print("學號:"+num+"姓名:"+name+"年齡:"+age+"學歷"+xueli);
}
結果如下:
輸入11242 張三 12 高中
輸出學號:11242姓名:張三年齡:12學歷高中
例子2:11242,張三,12,高中
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
String[] a=in.nextLine().split(",");
int num=Integer.valueOf(a[0]);
String name=a[1];
int age=Integer.valueOf(a[2]);
String xueli=a[3];
System.out.print("學號:"+num+"姓名:"+name+"年齡:"+age+"學歷"+xueli);
}
輸入11242,張三,12,高中
輸出學號:11242姓名:張三年齡:12學歷高中