I am attempting to split a string into a list of strings delimited on the change of if a character can be casted numerically or not. To say it another way, I want to break my string up into distinct groups of numbers and letters. For added fun, I'm also trying to trim any leading 0's from each group of numbers. Consider the following example.
Say you're given "aoeu01234stnh0987" as your input. The output I want is ["aoeu", "1234", "stnh", "987"]
I made a working example below, but it is somewhat long and confusing. It seems like there must be a better, more concise way to achieve this.
private static List<String> fragmentString(String string) {
char[] charArr = string.toCharArray();
StringBuilder tempStr = new StringBuilder();
StringBuilder tempInt = new StringBuilder();
List<String> tempList = new ArrayList<>();
boolean wasPrevNum = false;
for (char c : charArr) {
boolean isNum = Character.isDigit(c);
if (isNum) {
tempInt.append(c);
if (!wasPrevNum) {
wasPrevNum = true;
tempList.add(tempStr.toString());
tempStr = new StringBuilder();
}
} else {
tempStr.append(c);
if(wasPrevNum) {
while (tempInt.charAt(0) == '0') tempInt.deleteCharAt(0);
tempList.add(tempInt.toString());
tempInt = new StringBuilder();
wasPrevNum = false;
}
}
}
if (tempInt.length() > 0) while (tempInt.charAt(0) == '0') tempInt.deleteCharAt(0);
tempList.add(wasPrevNum ? tempInt.toString() : tempStr.toString());
return tempList;
}
I saw this post about using the split() method, but that solution only works for their very specific case and doesn't apply here. The split() method was the first thing I played with to solve this, but I couldn't figure out a regex, and now I'm questioning if this is even possible using split().