String[] split(xx)
根据给定的正则表达式的匹配来拆分此字符串。形成一个新的String数组。
可按照字符及空格拆分
@Test
public void test1(){
String str = "Hello World java";
String[] all = str.split(" ");
for (int i = 0; i < all.length; i++) {
System.out.println(all[i]);
}
}
也可以按照正则表达式拆分
@Test
public void test2(){
String str = "1Hello2World3java4aaaa";
str = str.replaceFirst("\\d", "");
System.out.println(str);
String[] all = str.split("\\d");
for (int i = 0; i < all.length; i++) {
System.out.println(all[i]);
}
}
@Test
public void test3(){
String str = "1Hello2World3java4aaaa5";
str = str.replaceAll("^\\d|\\d$", "");
String[] all = str.split("\\d");
for (int i = 0; i < all.length; i++) {
System.out.println(all[i]);
}
}
可以运用于给定数据拆分,然后进行类的包装
class Student{
private String name;
private int age;
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Student() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
}
@Test
public void test4(){
String str = "张三.23|李四.24|王五.25";
//|在正则中是有特殊意义,我这里要把它当做普通的|
String[] all = str.split("\\|");
//转成一个一个学生对象
Student[] students = new Student[all.length];
for (int i = 0; i < students.length; i++) {
//.在正则中是特殊意义,我这里想要表示普通的.
String[] strings = all[i].split("\\.");//张三, 23
String name = strings[0];
int age = Integer.parseInt(strings[1]);
students[i] = new Student(name,age);
}
for (int i = 0; i < students.length; i++) {
System.out.println(students[i]);
}
}
结果
版权声明:本文为Marblue_原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。