J2ME String Tokenizer:
public String[] split(String toSplit, char delim, boolean ignoreEmpty) {
StringBuffer buffer = new StringBuffer();
Stack stringStack = new Stack();
for (int i = 0; i < toSplit.length(); i++) {
if (toSplit.charAt(i) != delim) {
buffer.append((char) toSplit.charAt(i));
} else {
if (buffer.toString().trim().length() == 0 && ignoreEmpty) {
} else {
stringStack.addElement(buffer.toString());
}
buffer = new StringBuffer();
}
}
if (buffer.length() != 0) {
stringStack.addElement(buffer.toString());
}
String[] split = new String[stringStack.size()];
for (int i = 0; i < split.length; i++) {
split[split.length - 1 - i] = (String) stringStack.pop();
}
stringStack = null;
buffer = null;
return split;
}
用于调用它的方法:
String toSplit = myThreadObject.GetInfo();
String del = DelimiterValue.getString();
char delimiter = del.charAt(0);
String[] result = split(toSplit, delimiter, false);
if (result != null) {
for (int i = 0; i < result.length; i++) {
System.out.println("The elements are: " + result[i]);
}
} else {
System.out.println("The result is empty");
}
这是一个如何在J2ME中拆分字符串的示例,它实际上是从一个线程中拉出的网站中拆分html内容。 任何人都可以告诉我如何在此代码中添加一个简单的计数器来计算结果打印的次数,即有多少令牌?因为我在挣扎。
非常感谢
答案 0 :(得分:3)
无需添加计数器,因为数组具有公共.length
属性,可以为您公开计数。我在你的代码中添加了一行(以及它之前的注释)。我还删除了对result != null
的支票,因为您的split()
方法永远不会返回null
。如果没有匹配,则返回零长度数组。
String toSplit = myThreadObject.GetInfo();
String del = DelimiterValue.getString();
char delimiter = del.charAt(0);
String[] result = split(toSplit, delimiter, false);
// add the line below:
System.out.println("There are " + result.length + " results");
for (int i = 0; i < result.length; i++) {
System.out.println("The elements are: " + result[i]);
}