Java String - Phương thức split trong Java String
Phương thức split trong Java String
Phương thức split trong Java String
Phương thức split() tách chuỗi này theo biểu thức chính quy(regular expression) và trả về mảng chuỗi.
Phương thức:
public String split(String regex)
public String split(String regex, int limit)
Ví dụ 1:
public class SplitExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s1 = "java string split method by hiepsiit.com";
String[] words = s1.split("\\s");//tach chuoi dua tren khoang trang
//su dung vong lap foreach de in cac element cua mang chuoi thu duoc
for (String w : words) {
System.out.println(w);
}
}
}
Kết quả:
Ví dụ 2:
public class SplitExample2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
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);
}
}
}
Kết quả: