0

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
  • simply check if the word has a space before and after the character Commented Jun 24, 2015 at 9:28
  • 2
    Could you just use indexOf("> " + mTreeLevel + " >") + 2? Commented Jun 24, 2015 at 9:29

2 Answers 2

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

Assume I have this string "Files > Cold C Storage > C > Capital" then it will get the wrong occurrence for ` C ` !!
@blueware You can search for "> C >" instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.