Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String previous last index

Tags:

java

csv

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.

like image 834
techie2k Avatar asked May 28 '12 14:05

techie2k


2 Answers

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.

like image 173
NPE Avatar answered Sep 22 '22 09:09

NPE


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'

like image 37
Sackurise Avatar answered Sep 23 '22 09:09

Sackurise