2

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 /?

deer deer
  • 49
  • 5
  • 4
    Given that it's a filename, I'd start with `java.io.File`. Alternatively, `String.lastIndexOf` and `String.substring` if you really want to. – Jon Skeet Nov 12 '14 at 21:57
  • It is a filename, but I'm not really working with files, but filenames or filepaths, that's why I don't consider `java.io.File`. Am I wrong with my line of thought? – deer deer Nov 12 '14 at 22:00
  • 2
    Yes, because `java.io.File` is precisely an abstract filename. It doesn't require the file to *exist*. – Jon Skeet Nov 12 '14 at 22:01
  • Thank you. I'm going to use lastIndexOf, but thanks nonetheless, I'll probably use your advice too sometime later. – deer deer Nov 12 '14 at 22:04

3 Answers3

4

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);
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1
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;
}
aebal
  • 11
  • 2
0

May be you can use something like this,

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

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

pikachu
  • 63
  • 5