deer deer
deer deer

Reputation: 49

How to get a part of a string in java?

Basically, I have these strings:

/path/to/Pbox01/file1_#$%encryp
/path/to/Pbox01/file4_#$%encryp
/path/to/Pbox02/file2_#$%encryp

And I want to get ONLY file1, file4, file2 for each iteration. Those are filenames, and they can be anything(like file, stack, blahblahblah. First I want to get the part after the last slash - this is the part I'm having biggest problems with. The ending is hardset, so I want to trim _#$%encryp, which is 10 characters - for that I'll use:

public String removeLastChar(String s) {
    if (s == null || s.length() == 0) {
        return s;
    }
    return s.substring(0, s.length()-10);
}

So, to summarize, the question is: How can I get the part of the string after the last /?

Upvotes: 2

Views: 184

Answers (3)

aebal
aebal

Reputation: 11

public void changetomain(String [] args) {

    ArrayList<String> paths = new ArrayList<String>();
    paths.add("/path/to/Pbox01/file1_#$%encryp");
    paths.add("/path/to/Pbox01/file2_#$%encryp");
    paths.add("/path/to/Pbox01/file4_#$%encryp");

    ArrayList<String> filenames = getFilenames(paths);  

}

private ArrayList<String> getFilenames(ArrayList<String> paths) {
    ArrayList<String> filenames = new ArrayList<String>();
    for(String path : paths) {
        String filename = path.substring(path.lastIndexOf("/") + 1, path.indexOf("_"));
        filenames.add(filename);
    }

    return filenames;
}

Upvotes: 1

pikachu
pikachu

Reputation: 63

May be you can use something like this,

String[] strArray = str.split("/");

Then take only the last value in the array to process further.

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201447

I think you might use String.lastIndexOf(int) like,

public String removeLastChar(String s) {
  if (s == null || s.length() == 0) {
    return s;
  }
  return s.substring(s.lastIndexOf('/') + 1, s.length() - 10);
}

Upvotes: 4

Related Questions