views:

282

answers:

1

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;
}

Method Used To Call It:

        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");
        }

This is an example of how to split up a string in J2ME, it is actually splitting up html content from a website pulled in a thread. Can anyone tell me how I add a simple counter into this code to count the number of times the result is printed out, i.e. how many tokens there are? Because i am struggling.

Many thanks

+2  A: 

No need to add a counter as the array has the public .length property which exposes the count for you. I added one line to your code (and a comment immediately before it). I also removed your check for result != null because your split() method will never return null. It returns a zero length array if there are no matches.

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