Reputation: 5381
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!
Upvotes: 0
Views: 228
Reputation: 65851
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);
}
Upvotes: 1
Reputation: 393936
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.
Upvotes: 1