如何在J2ME中拆分字符串?

时间:2008-10-14 11:12:05

标签: java algorithm string java-me

如何以有效的方式在J2ME中拆分字符串?

标准版(J2SE)中有StringTokenizerString.split(String regex),但微版本(J2ME,MIDP)中没有它们。

8 个答案:

答案 0 :(得分:11)

J2ME的StringTokenizer类有一些实现。这个Ostermiller很可能包含您需要的功能

另请参阅this page on Mobile Programming Pit Stop进行一些修改以及以下示例:

String firstToken;
StringTokenizer tok;

tok = new StringTokenizer("some|random|data","|");
firstToken= tok.nextToken();

答案 1 :(得分:3)

没有内置的方法来分割字符串。你必须自己编写它 String.indexOf()String.substring()。不难。

答案 2 :(得分:3)

String.split(...)在J2SE中可用,但不在J2ME中 您需要编写自己的算法:related post with sample solution

答案 3 :(得分:3)

我希望这个会帮助你...这是我在我的应用程序中使用的我自己的实现。当然,这仍然可以优化。我没有时间去做...而且,我在这里工作的是StringBuffer。只需重构一下就可以使用String了。

public static String[] split(StringBuffer sb, String splitter){
    String[] strs = new String[sb.length()];
    int splitterLength = splitter.length();
    int initialIndex = 0;
    int indexOfSplitter = indexOf(sb, splitter, initialIndex);
    int count = 0;
    if(-1==indexOfSplitter) return new String[]{sb.toString()};
    while(-1!=indexOfSplitter){
        char[] chars = new char[indexOfSplitter-initialIndex];
        sb.getChars(initialIndex, indexOfSplitter, chars, 0);
        initialIndex = indexOfSplitter+splitterLength;
        indexOfSplitter = indexOf(sb, splitter, indexOfSplitter+1);
        strs[count] = new String(chars);
        count++;
    }
    // get the remaining chars.
    if(initialIndex+splitterLength<=sb.length()){
        char[] chars = new char[sb.length()-initialIndex];
        sb.getChars(initialIndex, sb.length(), chars, 0);
        strs[count] = new String(chars);
        count++;
    }
    String[] result = new String[count];
    for(int i = 0; i<count; i++){
        result[i] = strs[i];
    }
    return result;
}

public static int indexOf(StringBuffer sb, String str, int start){
    int index = -1;
    if((start>=sb.length() || start<-1) || str.length()<=0) return index;
    char[] tofind = str.toCharArray();
    outer: for(;start<sb.length(); start++){
        char c = sb.charAt(start);
        if(c==tofind[0]){
            if(1==tofind.length) return start;
            inner: for(int i = 1; i<tofind.length;i++){ // start on the 2nd character
                char find = tofind[i];
                int currentSourceIndex = start+i;
                if(currentSourceIndex<sb.length()){
                    char source = sb.charAt(start+i);
                    if(find==source){
                        if(i==tofind.length-1){
                            return start;
                        }
                        continue inner;
                    } else {
                        start++;
                        continue outer;
                    }
                } else {
                    return -1;
                }

            }
        }
    }
    return index;
}

答案 4 :(得分:2)

这取决于你想要实现的目标,但函数String.substring()将在某处:

String myString = "Hello World";

这将打印从索引6开始到字符串结尾的子字符串:

System.out.println(myString.substring(6));

这将打印从索引0开始直到索引5的子字符串:

System.out.println(myString.substring(0,5));

输出上述所有代码:

World
Hello

将此与其他字符串函数(indexOf()等)相结合,以达到预期的效果!

重新阅读您的问题,看起来您可能一直在寻找String.split()。这将根据给定的正则表达式将输入字符串拆分为字符串数组:

String myString = "Hi-There-Gang";

String[] splitStrings = myString.split("-");

这将导致splitStrings数组包含三个字符串"Hi""There""Gang"

再次重新阅读您的问题,String.split在J2ME中不可用,但使用substringindexOf可以达到同样的效果。

答案 5 :(得分:1)

public static Vector splitDelimiter(String text, char delimiter) {
    Vector splittedString = null;
    String text1 = "";

    if (text != null) {
        splittedString = new Vector();
        for (int i = 0; i < text.length(); i++) {
            if (text.charAt(i) == delimiter) {
                splittedString.addElement(text1);
                text1 = "";
            } else {
                text1 += text.charAt(i);
                // if(i==text.length()-1){
                // splittedString.addElement(text1);
                // }
            }
        }
        splittedString.addElement(text1);
    }
    return s
     }

您可以使用此方法拆分分隔符。

答案 6 :(得分:1)

在J2ME中没有拆分,但是您可以使用此代码进行拆分。此代码仅适用于1个simbol分隔符! 使用NetBeans.File \ Create Project \ Java ME \ MobileApplication \设置项目名称(拆分)\设置checkmark.Delete(Midlet.java)中的所有代码。复制此代码并过去(Midlet.java)。

//IDE NetBeans 7.3.1
//author: UserSuperPupsik 
//email: usersuperpupsik@gmail.com



package split;


import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import java.util.Vector;

public class Midlet extends MIDlet {
 public String e1;
    public Vector v=new Vector();
 public int ma;
 int IsD=0;
 int vax=0;
 public String out[];
 private Form f;

 public void split0(String text,String delimiter){
                            if (text!=""){
                            IsD=0;

                            int raz=0;

                            //v.removeAllElements();
                            v.setSize(0);
                            int io;
                            String temp=""; 
                             int ni=(text.length()-1);


                             for(io=0;io<=ni;io++){

                                    char ch=text.charAt(io);
                                    String st=""+ch;                                    
                                    if(io==0 && st.equals(delimiter)){IsD=1;}

                                    if(!st.equals(delimiter)){temp=temp+st;} //Not equals (!=)
                                    else if(st.equals(delimiter)&&temp!="")//equals (==)
                                                                {
                                    IsD=1;
                                    //f.append(temp);   
                                    v.addElement(temp);
                                    temp="";                   

                                                                 }


                                     if(io==ni && temp!="") {
                                              v.addElement(temp);
                                              temp="";  
                                              }           

                                     if((io==ni)&&IsD==0&&temp!=""){v.addElement(temp);}




                                            }



                                       if(v.size()!=0){

                                       ma=(v.size());

                                       out=new String[ma];


                                       v.copyInto(out);

                                       }
                                       //else if(v.size()==0){IsD=1; }


                            }
                                 }


public void method1(){
    f.append("\n");
    f.append("IsD: " +IsD+"");
    if (v.size()!=0){
    for( vax=0;vax<=ma-1;vax++){
                                f.append("\n");

                                f.append(out[vax]);


                                    }
                          }  
}
    public void startApp() {

    f=new Form("Hello J2ME!");
    Display.getDisplay(this).setCurrent(f);

    f.append("");
    split0("Hello.World.Good...Luck.end" , ".");
    method1();

    split0(".",".");
    method1();

    split0("   First WORD2 Word3 "," ");
    method1();

    split0("...",".");
    method1();            
                                                }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }




}

位于数组中的Splited元素称为(out)。例如out [1]:Hello。 祝你好运!!!

答案 7 :(得分:0)

另一种替代解决方案:

 public static Vector split(String stringToSplit, String separator){
     if(stringToSplit.length<1){
         return null;
     }

     Vector stringsFound = new Vector();

     String remainingString = stringToSplit;

     while(remainingString.length()>0){
         int separatorStartingIndex = remainingString.indexOf(separator);

         if(separatorStartingIndex==-1){
             // Not separators found in the remaining String. Get substring and finish
             stringsFound.addElement(remainingString);
             break;
         }

         else{
             // The separator is at the beginning of the String,
             // Push the beginning at the end of separator and continue
             if(remainingString.startsWith(separator)){
                 remainingString = remainingString.substring(separator.length());
             }
             // The separator is present and is not the beginning, add substring and continue
             else{
                 stringsFound.addElement(remainingString.substring(0, separatorStartingIndex));
                 remainingString = remainingString.substring(separatorStartingIndex + separator.length());
             }
         }
     }

     return stringsFound;
 }