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

0

I have a string and I 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 that is between the first "/" until the second "/" and in town from the second "/" to the third "/" but 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.dgsystems.criappstore.MainActivity.onCreate (MainActivity.java:103)

    
asked by anonymous 20.03.2018 / 00:12

1 answer

10

It would not be easier to use the 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
  

Running at repl

    
20.03.2018 / 00:19