mercredi 11 mars 2015

Using Java, I need to split a string into sections into an arrayList between 2 capital letters

I need to split a string into substrings and record the results in an ArrayList. Substrings will be delimited by pairs of capital letters, with each pair included in the preceding substring. For example, if the string was:


String testString = "Linda Dumas 3393 Pennsylvania Avenue Portland TX Huazhang Hanlon 3428 Main Road Miami NH ";


The output would be {"Linda Dumas 3393 Pennsylvania Avenue Portland TX", "Huazhang Hanlon 3428 Main Road Miami NH"}


The actual input string has about 200 addresses. I’ve tried using regular expressions to do this, but I just get the return of the two capital letters. I was thinking you would use this in a substring method but kept getting too many errors doing that. Any help is appreciated.


This is what I had before I started receiving errors (yes I know there is a problem with the testString.charAt(q+2) and q+1):



String testString = "Linda Dumas 3393 Pennsylvania Avenue Portland TX Huazhang Hanlon 3428 Main Road Miami NH ";
List<String> allMatches = new ArrayList<String>();
Matcher m = Pattern.compile("[A-Z]{2}").matcher(testString);
for (int q = 0; q < testString.length() - 1; q++){
if (Character.isUpperCase(testString.charAt(q))
&& Character.isUpperCase(testString.charAt(q + 1))){
address = new StringBuilder().append(testString.charAt(q)).append(testString.charAt(q+2)).toString();
list.add(address);
}
}
// System.out.println(list);
while (m.find()) {
allMatches.add(m.group());
}
System.out.println(allMatches);

Aucun commentaire:

Enregistrer un commentaire