当前位置: 代码迷 >> J2ME >> J2ME字符串split步骤
  详细解决方案

J2ME字符串split步骤

热度:1424   发布时间:2013-02-25 21:31:56.0
J2ME字符串split方法
/**  * Split string into multiple strings  * @param original      Original string * @param separator     Separator string in original string * @return              Splitted string array */private String[] split(String original, String separator) {    Vector nodes = new Vector();     // Parse nodes into vector    int index = original.indexOf(separator);    while(index>=0) {        nodes.addElement( original.substring(0, index) );        original = original.substring(index+separator.length());        index = original.indexOf(separator);    }    // Get the last node    nodes.addElement( original );     // Create splitted string array    String[] result = new String[ nodes.size() ];    if( nodes.size()>0 ) {        for(int loop=0; loop<nodes.size(); loop++)        result[loop] = (String)nodes.elementAt(loop);    }    return result;}/**  * Split string into multiple strings  * @param original      Original string * @param separator     Separator string in original string * @return              Splitted string array */private Vector split2Vector(String original, String separator) {    Vector nodes = new Vector();    // Parse nodes into vector    int index = original.indexOf(separator);    while(index>=0) {        nodes.addElement( original.substring(0, index) );        original = original.substring(index+separator.length());        index = original.indexOf(separator);    }    // Get the last node    nodes.addElement( original );    return nodes;}
?
1 楼 Silence_Smile 2011-01-22  
有个bug,把最后剩下的内容加入nodes之前,需要判断下长度,否则有可能加入一个空字符串
    /**     * Split string into multiple strings     * @param original      Original string     * @param separator     Separator string in original string     * @return              Splitted string array     */    private String[] split(String original, String separator) {        Vector nodes = new Vector();        // Parse nodes into vector        int index = original.indexOf(separator);        while (index >= 0) {            nodes.addElement(original.substring(0, index));            original = original.substring(index + separator.length());            index = original.indexOf(separator);        }        // Get the last node        if(original.length()>0){            nodes.addElement(original);        }        // Create splitted string array        String[] result = new String[nodes.size()];        if (nodes.size() > 0) {            for (int loop = 0; loop < nodes.size(); loop++) {                result[loop] = (String) nodes.elementAt(loop);            }        }        return result;    }