gpt4 book ai didi

java - 使用 StringTokenizer 模拟 String.split

转载 作者:行者123 更新时间:2023-11-30 06:23:59 25 4
gpt4 key购买 nike

我正在将现有应用程序的代码转换为针对定制硬件的 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()]);
}

关于java - 使用 StringTokenizer 模拟 String.split,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17588872/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com