学生类:
public class Student {
private String stuId;
private String name;
private int score;
public String getStuId() {
return stuId;
}
public Student setStuId(String stuId) {
this.stuId = stuId;
return this;
}
public String getName() {
return name;
}
public Student setName(String name) {
this.name = name;
return this;
}
public int getScore() {
return score;
}
public Student setScore(int score) {
this.score = score;
return this;
}
public Student(String stuId, String name, int score) {
this.stuId = stuId;
this.name = name;
this.score = score;
}
public Student() {
}
@Override
public String toString() {
return "Student{" +
"stuId='" + stuId + '\'' +
", name='" + name + '\'' +
", score=" + score +
'}';
}
}
测试类:
public class Test {
public static void main(String[] args) {
String text = "101,lisi,98;202,zhangsan,66;303,wangwu,88;404,chengqi,77;505,zhaoliu,44";
// 方法1:
String[] strings = text.split("[,;]");
Student[] stus = new Student[text.split(";").length];
for (int i = 0; i < strings.length; i+=3) {
Student stu = new Student();
stu.setStuId(strings[i]);
stu.setName(strings[i+1]);
stu.setScore(Integer.parseInt(strings[i+2]));
stus[i/3]=stu;
}
for (Student stu : stus){
System.out.println(stu);
}
// 方法2:
/*String[] strings = text.split("[,;]");
Student[] stus = new Student[10];
int size = 0;
for (int i = 0; i < strings.length; i+=3) {
if (size==strings.length){
Arrays.copyOf(stus, stus.length*2);
}
Student stu = new Student();
stu.setStuId(strings[i]);
stu.setName(strings[i+1]);
stu.setScore(Integer.parseInt(strings[i+2]));
stus[size]=stu;
size++;
}
for (int j=0;j<size;j++){
System.out.println(stus[j]);
}*/
// 方法3:
/*String[] students = text.split(";");
Student[] stus = new Student[students.length];
for (int i = 0; i < students.length; i++) {
String[] student = students[i].split(",");
Student stu = new Student();
stu.setStuId(student[0]);
stu.setName(student[1]);
stu.setScore(Integer.parseInt(student[2]));
stus[i]=stu;
}
for (Student stu : stus){
System.out.println(stu);
}*/
}
}
结果:
Student{stuId='101', name='lisi', score=98}
Student{stuId='202', name='zhangsan', score=66}
Student{stuId='303', name='wangwu', score=88}
Student{stuId='404', name='chengqi', score=77}
Student{stuId='505', name='zhaoliu', score=44}