How do I split strings in J2ME?
Asked Answered
S

8

14

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

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

Spannew answered 14/10, 2008 at 11:12 Comment(1)
A bit of a side note, doesn't help with J2ME, but might help others in the future... Unfortunately, StringTokenizer has been deprecated in J2SE. The suggested replacement is to just use the String split method. Rather unfortunate, StringTokenizer made for some nice slick code. Changing it around to just use the String split method makes for clunkier code. That does seem to be the Java way though, deprecate the good features and tell people to just use the clunky ones instead.Uncharted
C
11

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

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

String firstToken;
StringTokenizer tok;

tok = new StringTokenizer("some|random|data","|");
firstToken= tok.nextToken();
Coolidge answered 14/10, 2008 at 11:57 Comment(0)
G
4

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.

Gelt answered 14/10, 2008 at 11:16 Comment(3)
Yes, but will it be memory effective? String.substring() will create new strings, which will hog the memory until garbage collected.Spannew
StringTokenizer.nextToken() contains "return string.subString(...)" internally so I don't think you're any worse off...Leg
Substring uses a private constructof for String which shares the (immutable) char array, so yes - it will be memory efficient.Sharl
M
3

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

Mariomariology answered 14/10, 2008 at 11:51 Comment(0)
D
3

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.

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;
}
Duologue answered 27/7, 2010 at 12:42 Comment(1)
btw, here's how you can use the code... String[] elements = split(new StringBuffer("Hello|World"), "|"); or String[] elements = split(new StringBuffer("HelloblahWorld"), "blah"); both returns {"Hello", "World"}Duologue
E
2

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

String myString = "Hello World";

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

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

This will print the substring starting from index 0 until index 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!

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 myString = "Hi-There-Gang";

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

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

Re-reading your question again, String.split is not available in J2ME, but the same effect can be achieved with substring and indexOf.

Elephantine answered 14/10, 2008 at 11:35 Comment(0)
I
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
     }

You can use this method for splitting a delimiter.

Inmate answered 25/9, 2012 at 8:47 Comment(0)
M
1

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).

//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!!!

Maclean answered 29/9, 2013 at 17:10 Comment(0)
B
0

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;
 }
Braley answered 19/8, 2014 at 10:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.