在应用程序中,有一个字符串,格式如下:
String elements ="[11,john,] [23,Adam,] [88,Angie,] ......"(...表示字符串中有更多元素)
从给定的字符串我必须为名称ID(11,23,88,...)创建一个ArrayList,为名称创建一个ArrayList(john,Adam,Angie,...)
我创建了两种方法:
private int getItemID(int listLocation, String inputString){
int indexBeginning = inputString.indexOf("[", listLocation) + 1;
int indexEnd = inputString.indexOf(",", listLocation) - 1;
String sID = inputString.substring(indexBeginning, indexEnd);
int result = Integer.parseInt(sID);
return result;
}
private String getItemName(int listLocation, String inputString){
int indexBeginning = inputString.indexOf(" ", listLocation) + 1;
int indexEnd = inputString.indexOf(",", indexBeginning) - 1;
String result = inputString.substring(indexBeginning, indexEnd);
return result;
}
Run Code Online (Sandbox Code Playgroud)
并打算在方法parseArrayString(String inputString)中使用这两个方法,我还没有编写但是可以按以下方式工作:
private void parseCommunityList(String inputString){
int currentLocation = 0;
int itemsCount = count the number of "[" characters in the string
for(int i = 0; i < itemsCount; i++)
{
currentLocation = get the location of the (i)th character "[" in the string;
String name = getItemName(currentLocation, inputString);
int ID = getItemID(currentLocation, inputString);
nameArray.Add(name);
idArray,Add(ID);
}
}
Run Code Online (Sandbox Code Playgroud)
如果你们中的任何人能够提出任何更简单的方法来从给定的字符串创建两个ArrayLists,我将不胜感激.
谢谢!
我建议使用正则表达式,使用组捕获所需的元素.下面的示例创建了一个Person对象列表,而不是单独的Strings 列表- 封装了其他海报建议的数据:
List<Person> people = new ArrayList<Person>();
String regexpStr = "(\\[([0-9]+),\\s*([0-9a-zA-Z]+),\\])";
String inputData = "[11, john,][23, Adam,][88, Angie,]";
Pattern regexp = Pattern.compile(regexpStr);
Matcher matcher = regexp.matcher(inputData);
while (matcher.find()) {
MatchResult result = matcher.toMatchResult();
String id = result.group(2);
String name = result.group(3);
Person person = new Person(Long.valueOf(id), name);
people.add(person);
}
Run Code Online (Sandbox Code Playgroud)
还有一个封装数据的简单类:
public class Person {
private Long id;
private String name;
public Person(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
// TODO equals, toString, hashcode...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12310 次 |
| 最近记录: |