'String previous last index

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.



Solution 1:[1]

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.

Solution 2:[2]

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'

Solution 3:[3]

To get previous last string

This - https://developer.co/RTsMlGTsCj/share

To - RTsMlGTsCj

Use this

Kotlin

val removeDomainName : String = scanResult.substring(
                scanResult.lastIndexOf('/', scanResult.lastIndexOf('/') - 1),
                scanResult.lastIndexOf('/')
            )
            val profileCode: String = removeDomainName.removePrefix("/")

Java

String removeDomainName = scanResult.substring(scanResult.lastIndexOf('/',scanResult.lastIndexOf('/')-1),scanResult.lastIndexOf('/'));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 NPE
Solution 2 Sackurise
Solution 3 Sumit Ojha