Previous last index row

Is there an easy way to get the penultimate separable string substring?

String original = "/1/6/P_55/T_140";

In this example, the resulting substring will be "P_55/T_140"

I would like to find the forward slash index at the beginning of this substring ( /)

I know that String.lastIndexOf()calling twice will help. But the search for a cleaner approach that is common. Perhaps for any N.

+5
source share
2 answers

But the search for a cleaner approach that is common. Perhaps for any N.

The call String.lastIndexOf(int,int)in the loop will be quite efficient and possibly quite clean:

    int pos = str.length();
    for (int i = 0; i < n; i++) {
        pos = str.lastIndexOf('/', pos - 1);
    }
    String out = str.substring(pos + 1);

It can be easily converted into an auxiliary function that takes str, '/'and n, and returns out.

+8

,

/storage/emulated/0/WhatsApp/Media/WhatsApp Video/VID-20170812-WA0000.mp4

String folderName = filePath.substring(filePath.lastIndexOf('/',filePath.lastIndexOf('/')-1),filePath.lastIndexOf('/'));

_ "WhatsApp Video"

0

All Articles