java - Simulating String.split using StringTokenizer -


i'm converting code existing application to compile against java 1.1 compiler custom piece of hardware. means i can't use string.split(regex) convert existing string array.

i created method should give same result string.split(regex) there's wrong , 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 i'm trying 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 ]

i modified code , tested it. works (don't forget avoid hard-coding "," can use function delimiter):

private static string[] split(string delim, string line) {      stringtokenizer tokens = new stringtokenizer(line, delim, true);     string previous = delim;     vector v = new vector();      while (tokens.hasmoretokens()) {         string token = tokens.nexttoken();          if (!delim.equals(token)) {             v.add(token);         } else if (previous.equals(delim)) {             v.add("");         }         previous = token;     }      return (string[]) v.toarray(new string[v.size()]); } 

Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -