I am trying to do the following in Java
give a directory path like "/a/b/c" I want to get a array of string as ["a", "b", "c"]. The code is as follows :
private static final String DIRECTORY_PATH_SEPARATOR = "/";
Iterator iter = testPaths.iterator();
String[] directories;
while( iter.hasNext() ) {
directories = ( ( String ) iter.next() ).split(DIRECTORY_PATH_SEPARATOR);
}
but what i get as array is space as well. I want to get all those strings with length>0.
how can I do that??
The only place you’d get an empty string (in a valid path) would be the first item if the path started with the separator. If it had the leading separator, split on the path without it.
As noted by OmnipotentEntity, my assumption was wrong about valid paths. You’d otherwise have to go through the array and keep nonempty strings when using
split().An alternative is to use actual regular expressions to match non-separator characters: