Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string logic in J2ME

Tags:

java-me

I am developing a J2ME application.

I want to split the following string at "<br>" & comma:

3,toothpaste,2<br>4,toothbrush,3

How can I do this?

like image 320
Vikas Avatar asked Mar 18 '09 10:03

Vikas


People also ask

How do you split a string?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

How to split a string on in Java?

string. split("\\|"); Splits the string variable at the | character. We use two backlashes here since we need to first escape the Java-meaning of the backlash, so the backslash can be applied to the | character.

How to split a string in Java using regex?

split(String regex) method splits this string around matches of the given regular expression. This method works in the same way as invoking the method i.e split(String regex, int limit) with the given expression and a limit argument of zero.

What is split() in Java?

The method split() splits a String into multiple Strings given the delimiter that separates them. The returned object is an array which contains the split Strings. We can also pass a limit to the number of elements in the returned array.


1 Answers

  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 split 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);
            System.out.println(result[loop]);
        }

    }
   return result;
}

The above method will let you split a string about the passed separator, much like J2EE's String.split(). So first split the string on the line break tag, and then do it at each offset of the returned array for the "," comma. e.g.

 String[] lines = this.split(myString,"<br>");
 for(int i = 0; i < lines.length; i++) 
 {
      String[] splitStr = this.split(lines[i],",");
      System.out.println(splitStr[0] + " " + splitStr[1] + " " + splitStr[2]);     
 }
like image 137
karim79 Avatar answered Sep 26 '22 02:09

karim79