9

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Vikas
  • 24,082
  • 37
  • 117
  • 159

2 Answers2

18
  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]);     
 }
karim79
  • 339,989
  • 67
  • 413
  • 406
  • Should read : `// Get the last node if (!"".equals(original_element)) { nodes.addElement(original_element); }` – Mr_and_Mrs_D Mar 07 '12 at 22:55
  • Why did you revert my edit ? There is a bug - I run into it using your code - if the string has the form `` the result will be `[, ""]` - Please correct ! – Mr_and_Mrs_D Mar 08 '12 at 10:00
1
private String[] split(String original, String separator, int count)
{
    String[] result;
    int index = original.indexOf(separator);
    if(index >= 0)
        result = split(original.substring(index + separator.length()), separator, count + 1);
    else
    {
        result = new String[count + 1];
        index = original.length();
    }
    result[count] = original.substring(0, index);
    return result;
}

String[] lines = this.split(myString,"<br>",0);
Dionis
  • 11
  • 1