1

Possible Duplicate:
How do I split strings in J2ME?

I have a String data which is like csv , that is there are ";" inside the String data. But in my case there is always a ";" at the end of the String. I want to create a method which gives a String at a certain number from this csv. For example :

String csv = "145557;123456789012;Michael Robert;1000000;200000;;12/05/2011;;" ;

In this String there are 8 "columns". I say "column" the data between two ";" ( the first column is not enclosed by two ";" but only the one at its right ).

In this example the data "Michael Robert" has the number 2 ( or 3 if we start at 1 for the first column ).

So how to get the data ( column ) at a specified number ?

NB : I use Java ME

Community
  • 1
  • 1
  • 1
    Use `StringTokenizer`. Take a look at this duplicate question: [How do I split strings in J2ME?](http://stackoverflow.com/q/200746/851811) – Xavi López Sep 30 '11 at 09:21

4 Answers4

2

In J2ME you can write a method like this:

public class Main {

    public static void main(String[] args) {
        String csv = "145557;123456789012;Michael Robert;1000000;200000;;12/05/2011;;" ;
        System.out.println(getColumnAt(csv, 0));
        System.out.println(getColumnAt(csv, 1));
        System.out.println(getColumnAt(csv, 2));
    }

    public static String getColumnAt(String csv, int column) {
        int fromIndex = 0;
        int col = 0;
        while (col < column) {
            fromIndex = csv.indexOf(";", fromIndex) + 1;
            col++;
        }
        int toIndex = csv.indexOf(";", fromIndex);
        return csv.substring(fromIndex, toIndex);
    }
}

UPDATE: By the way, due to the way that substring is implemented it is better to return new String(csv.substring(fromIndex, toIndex));, otherwise the substring will hold a reference to the original string and then as long as the substring is not GC-able, the original String won't be GC-able as well.

Behrang
  • 46,888
  • 25
  • 118
  • 160
2

just use StringTokenizer:

StringTokenizer tok = new StringTokenizer(yourString,";");
column1 = tok.nextToken();
column2 = tok.nextToken();
...

Here you can find a more complex example.

Regards, Luca

Maverik
  • 2,358
  • 6
  • 34
  • 44
-2
csv.split(";")[2]; // returns "Michael Robert"

This uses the String.split(String delimiter) method, which splits the string around the delimiter, returning an array containing the resulting substrings.

mcfinnigan
  • 11,442
  • 35
  • 28
-2

Do you mean like this:

    public TestClass()
{
    String csv = "145557;123456789012;Michael Robert;1000000;200000;;12/05/2011;;" ;
    System.out.println(splitString(csv,2));
}

public String splitString(String s, int getValueAt)
{
    return s.split(";")[getValueAt];
}
Xavjer
  • 8,838
  • 2
  • 22
  • 42