David Navarre
David Navarre

Reputation: 1022

Removing a substring from a string

I have a very simple question and just can't get my code to work in Java. I want to return a string that indicates a filepath, but extracts a certain portion of that path if it it exists.

So, my input might be "c:/lotus/notes/data/directory/mydatabase.nsf" and I want to return only "directory/mydatabase.nsf". Sometimes, the path provided will already leave out the "c:/lotus/notes/data/" because it is being accessed on the server rather than locally.

public String getDataPath ( String path ) {
    int pathStart;
    boolean pathContains;
    String lowerPath;

    lowerPath = path.toLowerCase();
    pathStart = lowerPath.indexOf("c:/lotus/notes/data");

    if ( pathStart >= 0) {
        // 20 characters in "c:/lotus/notes/data/"
        return path.substring(19);
    }

    pathContains = lowerPath.contains("lotus/notes/data");
    if ( pathContains ) {
        // 20 characters in "c:/lotus/notes/data/"
        return path.substring(19);
    }

    return path;
}

This is simple, but somehow, I can't get it right. Neither of my if's ever evaluates as true.

Upvotes: 0

Views: 282

Answers (3)

Sebastian Hoffmann
Sebastian Hoffmann

Reputation: 11502

Take a look at the Path interface:

It is used to do exactly what you want: Extract informations about the single parts of a path.

Upvotes: 0

Kevin Bowersox
Kevin Bowersox

Reputation: 94489

Keep it simple:

path.replace("c:/lotus/notes/data", "");

Upvotes: 2

arynaq
arynaq

Reputation: 6870

You can simply do a path.replaceAll("c:/lotus/notes/data", ""). This will remove the leading path name if it is contained in the string, else the string will not change.

Upvotes: 2

Related Questions