I'm converting code from an existing application to compile against a Java 1.1 compiler for a custom piece of hardware. This means that I can't use String.split(regex)
to convert my existing string into an array.
I created a method which should give the same result as String.split(regex)
but there's something wrong with it and I can't figure out what.
Code:
private static String[] split(String delim, String line) {
StringTokenizer tokens = new StringTokenizer(line, delim, true);
String previous = "";
Vector v = new Vector();
while(tokens.hasMoreTokens()) {
String token = tokens.nextToken();
if(!",".equals(token)) {
v.add(token);
} else if(",".equals(previous)) {
v.add("");
} else {
previous = token;
}
}
return (String[]) v.toArray(new String[v.size()]);
}
Sample input:
RM^RES,0013A2004081937F,,9060,1234FF
Sample output:
String line = "RM^RES,0013A2004081937F,,9060,1234FF";
String[] items = split(",", line);
for(String s : items) {
System.out.println(" [ " + s + " ] ");
}
[ RM^RES ] [ 0013A2004081937F ] [ ] [ ] [ 9060 ] [ ] [ 1234FF ]
Desired output:
[ RM^RES ] [ 0013A2004081937F ] [ ] [ 9060 ] [ 1234FF ]
Old code that I'm trying to convert:
String line = "RM^RES,0013A2004081937F,,9060,1234FF";
String[] items = line.split(",");
for(String s : items) {
System.out.println(" [ " + s + " ] ");
}
[ RM^RES ] [ 0013A2004081937F ] [ ] [ 9060 ] [ 1234FF ]