I have a large string that contains fixed value fields, this group of fields can repeat from 0 to 40 times. I would like to parse this list into an arraylist but I am not sure of the best way to do this?
The string data is as follows,
CountryCode = 2 character
StateProv = 7 characters
PostalCode 开发者_开发知识库 = 10 characters
BuildingNum = 5 characters
There is no delimiter the pattern just repeats
any suggestion?
I'd probably just read repeated substrings:
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));
}
(Or perform the parsing in the boody of the loop, or whatever... the main point is you've got the substring.)
I tried this using a character array. I am sure it can be optimized and I would like to see what changes you could apply to make it faster. Here is my test:
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());
}
}
精彩评论