我正在将代码从现有应用程序转换为针对定制硬件的Java 1.1编译器。这意味着我不能使用String.split(regex)将现有的字符串转换为数组。

我创建了一种方法,该方法应提供与String.split(regex)相同的结果,但是它存在问题,我无法弄清楚是什么。

码:

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()]);
}


输入样例:


  RM ^ RES,0013A2004081937F ,, 9060,1234FF


样本输出:

String line = "RM^RES,0013A2004081937F,,9060,1234FF";
String[] items = split(",", line);

for(String s : items) {
    System.out.println(" [ " + s + " ] ");
}



  [RM ^ RES] [0013A2004081937F] [] [] [9060] [] [1234FF]


所需的输出:


  [RM ^ RES] [0013A2004081937F] [] [9060] [1234FF]




我要转换的旧代码:

String line = "RM^RES,0013A2004081937F,,9060,1234FF";
String[] items = line.split(",");

for(String s : items) {
    System.out.println(" [ " + s + " ] ");
}



  [RM ^ RES] [0013A2004081937F] [] [9060] [1234FF]

最佳答案

我修改了代码并对其进行了测试。它可以正常工作(不要忘记避免对“,”进行硬编码,因此您可以将函数用于任何定界符):

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()]);
}

09-13 08:06