我有一个包含固定值字段的大字符串,这组字段可以重复0到40次。我想将这个列表解析为一个arraylist,但我不确定最好的方法吗?
字符串数据如下,
CountryCode = 2 character
StateProv = 7 characters
PostalCode = 10 characters
BuildingNum = 5 characters
模式重复没有分隔符
任何建议?
答案 0 :(得分:5)
我可能只是阅读了重复的子串:
private static final int PATTERN_LENGTH = 24;
....
List<Location> list = new ArrayList<Location>();
if (text.length() % PATTERN_LENGTH != 0)
{
// throw an exception of some description; you haven't got valid data
}
for (int start = 0; start < text.length(); start += PATTERN_LENGTH)
{
list.add(Location.parse(text.substring(start, start + PATTERN_LENGTH));
}
(或者在循环的boody中执行解析,或者其他......主要的一点是你有子串。)
答案 1 :(得分:0)
我尝试使用字符数组。我确信它可以进行优化,我希望看到您可以应用哪些更改来加快速度。这是我的测试:
public class Test {
public static String bigString = "USARIZONA85123-123477777USWASHING78987-458711111USCOLORAD11111-111133333";
public List<String> getValues() {
List<String> seperatedValues = new ArrayList<String>();
char[] bigStringArray = bigString.toCharArray();
char[] temp = new char[24];
int j = 0;
for (int i=1; i < bigStringArray.length+1; i++) {
temp[j] = bigStringArray[i-1];
j++;
if (i%24 == 0) {
seperatedValues.add(String.valueOf(temp));
temp = new char[24];
j = 0;
}
}
return seperatedValues;
}
public static void main(String[] args) {
Test test = new Test();
System.out.println(test.getValues());
}
}