Domanda

Is there a simple way of getting the penultimate delimited substring of a string?

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

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

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

I know String.lastIndexOf() calling twice would help. But looking for a cleaner approach which is generic. Perhaps to any N.

È stato utile?

Soluzione

But looking for a cleaner approach which is generic. Perhaps to any N.

Calling String.lastIndexOf(int,int) in a loop is going to be quite efficient, and arguably pretty clean:

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

This can be easily turned into a helper function taking str, '/' and n, and returning out.

Altri suggerimenti

To get the folder name where the media file resides

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

use the below code

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

returns the folderName as 'whatsApp Video'

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top