gpt4 book ai didi

java - 分割字符串并保存到对象列表

转载 作者:行者123 更新时间:2023-12-01 13:34:45 26 4
gpt4 key购买 nike

我有一个字符串,我想从字符串缓冲区中分离出来并将其保存到对象的数组列表中。

我有一串数据,看起来像这样:

001>10102011>874837>Y>Y>TEST001>No\\002>11102011>8743834>Y>Y>null>No\\ 

\将表示保存到新对象。如何将此字符串保存到 List 列表中?

我的示例保存对象是

public class SaveObject{
private String obj1;
private String obj2;
private String obj3;
private String obj4;
private String obj5;
private String obj6;
private String obj7;

//getters and setters
}

我被困住了

    StringTokenizer st= new StringTokenizer(sb1.toString(),"\\\\");
int count = 0;
int total= st.countTokens();//count no of rows of data
System.out.println(total);

while(count<total){
while(st.hasMoreElements()){
tmpList.add(st.nextToken());
count++;
}
}

System.out.println(tmpList.size());

for(int j = 0; j<tmpList.size(); j++){
String str = tmpList.get(j);

StringTokenizer st2 = new StringTokenizer(str, ">");
while (st2.hasMoreElements()){

System.out.println(st2.nextToken());
// is it possible to save into ArrayList of objects here?
// I can see that the String can split into
// 001
// 10102011
// 874873
// Y
// Y
// TEST001
// No etc
/* using st.nextToken but I don't know how to continue from here. Pls help!! Thanks. I want to do something like
obj = new Object();
obj.saveObj1(...);
obj.saveObj2(...);
obj.saveObj3(...);
obj.saveObj4(...);
obj.saveObj5(...);
obj.saveObj6(...);
obj.saveObj7(...);
listsaveobj.add(obj); but it's not possible? */
}
}

最佳答案

这是提取数据的更好方法:

String s = "001>10102011>874837>Y>Y>TEST001>No\\\\002>11102011>8743834>Y>Y>null>No\\\\";
String[] rows = s.split("\\\\");
for (String r : rows) {
String[] cols = r.split(">");
for (String c : cols) {
System.out.print(c + "\t");
}
System.out.println();
}

关于java - 分割字符串并保存到对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21372327/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com