How to make code that uses string properties readable?

4

I have a string that uses parts of another String, how to make this code "cleaner"? Since it is very difficult to understand.

String sessionHash = dirPath.substring(dirPath.substring(0, dirPath.length() - 1).lastIndexOf("/"));
  

sessionHash: / 23980dc32e16792007de3343f1f99211 /

     

dirPath:   / home / daniela / oknok / data / uploads / 23980dc32e16792007de3343f1f99211 /

    
asked by anonymous 17.03.2015 / 19:48

2 answers

6

So I understand the method getname() produces the result you expect:

String sessionHash = new File(dirPath).getName();

Or to stay the same:

String sessionHash = "/" + new File(dirPath).getName() + "/";

See working on ideone .

    
17.03.2015 / 20:00
3

You can do this through the split ": it breaks a string into pieces using a regular expression as a delimiter. Breaking around the bar, and taking the penultimate piece (the last one is empty, since it is after the last bar) you get the result you want:

String[] partes = dirPath.split("/");
String sessionHash = "/" + partes[partes.length-2] + "/";

In the specific case of the slash, however, it is simpler to use the File class, such as suggested by bigown .

    
17.03.2015 / 20:00