简体   繁体   中英

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

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);
}
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;
}

May be you can use something like this,

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM