How to make readable the code that uses String properties?

Asked

Viewed 116 times

5

I have a string that uses parts of another string, how to make this code more "clean"? 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/

2 answers

7


  • 1

    +1 and if she wants the bars around (such as in the example) just add them via string concatenation.

  • @mgibsonbr changed to resolve this although I doubt that it is the intention to keep the bars. I was doing the same as you but I had an abortion because I didn’t think it would make me feel any better.

  • 1

    Apart from the substring double, does not improve much even... You would know if this proposed method, using the File, will give an equal result on a Windows system? (which uses "" instead of "/" as separator) I think will, but I’m without compiler here to test...

  • the intention was to keep the bars, thank you. Really much more readable and easy to maintain.

  • 1

    @mgibsonbr as far as I know will work, but also can not guarantee.

  • If I’m not mistaken, there’s a constant in the class File, to FileSeparator, which is best for this. Using the response value gets a little stuck to the OS for code execution.

  • @mutlei I agree but in this case will not generate a file name but a string that the author only where will use. From what I understood need to be so even independent from OS, therefore in this specific case should not be used the separator. Unless she says it has to be different.

Show 2 more comments

4

You can do this through the method split: it breaks a string into pieces using a regular expression as the delimiter. Breaking around the bar, and grabbing the penultimate piece (the last one is empty as 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 bar, however, it is simpler to use the class File, just as suggested by Maniero.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.