java 如何在 J2ME 中拆分字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/200746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 11:24:22  来源:igfitidea点击:

How do I split strings in J2ME?

javaalgorithmstringjava-me

提问by Spoike

How do I split strings in J2ME in an effective way?

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

There is a StringTokenizeror String.split(String regex)in the standard edition (J2SE), but they are absent in the micro edition (J2ME, MIDP).

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

采纳答案by Jonas Pegerfalk

There are a few implementations of a StringTokenizer class for J2ME. This one by Ostermillerwill most likely include the functionality you need

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

See also this page on Mobile Programming Pit Stopfor some modifications and the following example:

另请参阅有关 Mobile Programming Pit Stop 的此页面,了解一些修改和以下示例:

String firstToken;
StringTokenizer tok;

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

回答by Guido

There is no built in method to split strings. You have to write it on your own using String.indexOf()and String.substring(). Not hard.

没有内置的方法来拆分字符串。您必须使用String.indexOf()和自行编写它 String.substring()。不难。

回答by Llyle

String.split(...) is available in J2SE, but not J2ME.
You are required to write your own algorithm: related post with sample solution.

String.split(...) 在 J2SE 中可用,但在 J2ME 中不可用。
您需要编写自己的算法:带有示例解决方案的相关帖子

回答by demotics2002

I hope this one will help you... This is my own implementation i used in my application. Of course this can still be optimized. i just do not have time to do it... and also, I am working on StringBuffer here. Just refactor this to be able to use String instead.

我希望这个能帮助你......这是我在我的应用程序中使用的自己的实现。当然这个还是可以优化的。我只是没有时间去做……而且,我正在这里研究 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;
}

回答by Rob Bell

That depends on what exactly you want to achieve, but the function String.substring() will be in there somewhere:

这取决于您究竟想要实现什么,但函数 String.substring() 将在某处:

String myString = "Hello World";

This will print the substring starting from index 6 to the end of the string:

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

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

This will print the substring starting from index 0 until index 5:

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

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

Output of all the code above:

以上所有代码的输出:

World
Hello

Combine this with the other String functions (indexOf(). etc.) to achieve the desired effect!

将此与其他 String 函数(indexOf(). 等)结合以达到预期效果!

Re-reading your question, it looks as though you may have been looking for String.split(). This will split your input string into an array of strings based on a given regex:

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

String myString = "Hi-There-Gang";

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

This will result in the splitStrings array containing three string, "Hi", "There"and "Gang".

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

Re-reading your question again, String.splitis not available in J2ME, but the same effect can be achieved with substringand indexOf.

再次重读你的问题,String.split在J2ME中是没有的,但是用substring和可以达到同样的效果indexOf

回答by Rahul

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
     }

You can use this method for splitting a delimiter.

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

回答by UserSuperPupsik

In J2ME no split, but you can use this code for split.This code works with only 1 simbol delimiter!!! Use NetBeans.File\Create Project\ Java ME\ MobileApplication\Set project name(split)\Set checkmark.Delete all code in your (Midlet.java).Copy this code and past in your (Midlet.java).

在 J2ME 中没有拆分,但您可以使用此代码进行拆分。此代码仅适用于 1 个 simbol 分隔符!!!使用 NetBeans.File\Create Project\Java ME\MobileApplication\Set project name(split)\Set checkmark.Delete all code in your (Midlet.java)。复制此代码并粘贴到您的 (Midlet.java) 中。

//IDE NetBeans 7.3.1
//author: UserSuperPupsik 
//email: [email protected]



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 elements located in array called (out).For Example out[1]:Hello. Good Luck!!!

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

回答by Miguel Rivero

Another alternative solution:

另一种替代解决方案:

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