anuradha
anuradha

Reputation: 692

String tokenization using StringTokenizer in android

I am trying to formate a string which has been received from a json into a new formate. The actual string is [90.36855,23.750088333333334] and my target is to convert it into two different strings like 90.36855 and 23.750088333333334

I tried in the following way

String s = "[90.36855,23.750088333333334]";
StringTokenizer st = new StringTokenizer(s, "[");
String lat = st.nextToken();
String lon = st.nextToken();

But it shows FATAL EXCEPTION: main. How can I solve this issue?

Upvotes: 0

Views: 4845

Answers (4)

Rohit Gadia
Rohit Gadia

Reputation: 39

Try this.

String s = "[90.36855,23.750088333333334]";
        StringTokenizer st = new StringTokenizer(s,",");
        String lat = st.nextToken().substring(1);
        String lon = st.nextToken();
        lon = lon.substring(0,lon.length()-1)

Upvotes: 0

Sachin Gupta
Sachin Gupta

Reputation: 8378

here in this string [ comes only once. So in this line String lon = st.nextToken(); it wil throw you exception, as nextToken() is not available.

As the String is JSONArray, you can use org.json to get lat and lon.

E.g.:

String s = "[90.36855,23.750088333333334]";
JSONArray jsonArray = new JSONArray(s);
String lat = jsonArray.get(0);
String lon = jsonArray.get(1);

But if you don't want to use JSONArray then StringTokenizer can also do the trick for you. Just update regx with [],:

String s = "[90.36855,23.750088333333334]";
StringTokenizer st = new StringTokenizer(s, "[],");
String lat = st.nextToken();
String lon = st.nextToken();

Upvotes: 2

Sasi Kumar
Sasi Kumar

Reputation: 13358

Use this code

String s = "[90.36855,23.750088333333334]";
String result = s.replaceAll("[]","");
StringTokenizer st = new StringTokenizer(result, ",");
String lat = st.nextToken();
String lon = st.nextToken();

Upvotes: 0

Shree Krishna
Shree Krishna

Reputation: 8562

Just replace your code with this,

    String s = "[90.36855,23.750088333333334]";
    s = s.substring(1, s.length() - 1); //Trim first and last brackets
    StringTokenizer st = new StringTokenizer(s, ","); //pass comma as delimeter
    String lat = st.nextToken();
    String lon = st.nextToken();

Upvotes: 0

Related Questions