Java: IndexOf(String string) that returns wrong character

227 views Asked by At

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!

2

There are 2 answers

0
OldCurmudgeon On BEST ANSWER

A better approach would be to use a List of Strings.

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

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.