If you want to split the String
at the /
character, the String.split
method will work:
For example:
String s = "prefix/dir1/dir2/dir3/dir4";
String[] tokens = s.split("/");
for (String t : tokens)
System.out.println(t);
Output
prefix
dir1
dir2
dir3
dir4
Edit
Case with a /
in the prefix, and we know what the prefix is:
String s = "slash/prefix/dir1/dir2/dir3/dir4";
String prefix = "slash/prefix/";
String noPrefixStr = s.substring(s.indexOf(prefix) + prefix.length());
String[] tokens = noPrefixStr.split("/");
for (String t : tokens)
System.out.println(t);
The substring without the prefix "slash/prefix/"
is made by the substring
method. That String
is then run through split
.
Output:
Edit again
If this String
is actually dealing with file paths, using the File
class is probably more preferable than using string manipulations. Classes like File
which already take into account all the intricacies of dealing with file paths is going to be more robust.