How to extract String from a larger string separated by "/"

Asked

Viewed 96 times

0

I have a string and want to extract a substring see in my code:

 String link = "lojas/RJ/Macaé/Loja Modelo/pedidos_ativos/03-03-2018-8773";
    String uf = link.substring(link.lastIndexOf("/",0),link.lastIndexOf("/",1));
    String cidade =link.substring(link.lastIndexOf("/",1),link.lastIndexOf("/",2));
    Log.e("eutag","UF dada: "+uf);
    Log.e("eutag","cidade dada: "+cidade);

I need to return in Uf everything between the first "/" and the second "/" and in city from the second "/" to the third "/" however this my code has error:

Caused by: java.lang.Stringindexoutofboundsexception: length=57; regionStart=-1; regionLength=0 at java.lang.String.startEndAndLength(String.java:504) at java.lang.String.substring(String.java:1333) at com.dgsistemas.criappstore.MainActivity.onCreate(Mainactivity.java:103)

1 answer

10


It would not be easier to use the method split?

String link = "lojas/RJ/Macaé/Loja Modelo/pedidos_ativos/03-03-2018-8773";
String[] partes = link.split("/");
System.out.println(partes[0]); // lojas
System.out.println(partes[1]); // RH
System.out.println(partes[2]); // Macaé
System.out.println(partes[3]); // Loja Modelo
System.out.println(partes[4]); // pedidos_ativos
System.out.println(partes[5]); // 03-03-2018-8773

Functioning in repl

  • very good thank you very much

Browser other questions tagged

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