简体   繁体   中英

Java: IndexOf(String string) that returns wrong character

I am writing a file browser program that displays file directory path while a user navigates between folders/files.

I have the following String as file path:

"Files > Cold Storage > C > Capital"

I am using Java indexOf(String) method to return the index of 'C' character between > C > , but it returns the first occurrence for it from this word Cold .

I need to get the 'C' alone which sets between > C > . This is my code:

StringBuilder mDirectoryPath = new StringBuilder("Files > Cold Storage > C > Capital");
String mTreeLevel = "C";
int i = mDirectoryPath.indexOf(mTreeLevel);
if (i != -1) {
    mDirectoryPath.delete(i, i + mTreeLevel.length());
}

I need flexible solution that fits other proper problems Any help is appreciated!

Search for the first occurance of " C " :

String mTreeLevel = " C ";
int i = mDirectoryPath.indexOf(mTreeLevel);

Then add 1 to account to get the index of 'C' (assuming the String you searched for was found).

If you only want to delete the single 'C' character :

if (i >= 0) {
    mDirectoryPath.delete(i + 1, i + 2);
}

EDIT:

If searching for " C " may still return the wrong occurrence, search for " > C > " instead.

A better approach would be to use a List of String s.

public void test() {
    List<String> directoryPath = Arrays.asList("Files", "Cold Storage", "C", "Capital");
    int cDepth = directoryPath.indexOf("C");
    System.out.println("cDepth = " + cDepth);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM