Split String using comma as parameter

Asked

Viewed 2,941 times

0

I am trying to get the values of a Listview to send them to another screen by clicking on the item.

So I have the following code:

@Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String sttr = parent.getItemAtPosition(position).toString();
        System.out.println(sttr);

    }

The return of String is:

I/System.out﹕ {perref=May / 2015, tipcal=Cálculo Mensal, codcal=408}

How can I separate these 3 comma-separated values into 3 strings?

Has anyone ever come across the situation?

There’s some other way to do it?

4 answers

4

It’s like @Onaiggac says here.. Using the Split function.

If you need to use the values that have been separated, you can create an array of strings and then access them

String[] sol;
String sttr = parent.getItemAtPosition(position).toString();
sol = sttr.split(",");

Now if you want to call String 1 after the split:

...sol[0];

The second:

...sol[1];

and so on

1

You can use the method Split with regular expression

  String sttr = parent.getItemAtPosition(position).toString();
  for (String retval: sttr.split(",")){
     System.out.println(retval);
  }

The Split method will return an array of strings for each found comma.

1

You can use this format as well:

String[] separated = CurrentString.split(",");
separated[0];
separated[1];

-1

In addition to the @Onaiggac response, it is possible as follows (as @Math returned in another question):

        int iniPerRef = retorno.toString().indexOf("perref=")+7;
        int fimPerRef = retorno.toString().indexOf(",", iniPerRef);
        System.out.println(retorno.toString().substring(iniPerRef, fimPerRef));

        int iniTipCal = retorno.toString().indexOf("tipcal=")+7;
        int fimTipCal = retorno.toString().indexOf(",", iniTipCal);
        System.out.println(retorno.toString().substring(iniTipCal, fimTipCal));

        int iniCodCal = retorno.toString().indexOf("codcal=")+7;
        int fimCodCal = retorno.toString().indexOf("}", iniCodCal);
        System.out.println(retorno.toString().substring(iniCodCal, fimCodCal));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.