Java brain damage of the day: substr

jdavidb on 2008-01-25T20:12:05

In Java, if you want to write:

substr($str, 0, $n)

You have to write something like:

str.substring(0, min(n, str.length - 1))

Because if your second index is greater than the length of the string, Java throws an exception, rather than realizing you wanted everything that far, or to the end of the string if you can't go that far.

Update 2008-02-22T19:37Z: This is apparently completely wrong. I realized that the next day, when I saw how one of my coworkers solved the same problem I was working on, and substring seemed to work for him. I have no idea why it didn't work for me. But I saw this today and thought, "Ew, I'd hate for anyone to read this and think it were actually true."


idiomatic?

slanning on 2008-01-27T04:38:40

I don't know much Java, but one of the criticisms of some Perl programmers is that they program Perl in C (i.e. using C idioms like for(i=0;i<N;i++)). Is it possible that using substring like that in Java is just a bad "translation" from Perl to Java, and there is a more natural Java-esque way to do it (not necessarily including only that particular statement, but possibly also the larger problem you're working on; e.g. it might be more natural to use an input stream and read from it or whatever -- I dunno just wondering).

Re:idiomatic?

davegaramond on 2008-02-16T01:30:46

I think the moral of the story is that Java throws exception for the littlest things. If I try to open a file and it fails, an exception is a sensible thing, as the next lines in the code would expect the file handle to be there.

But if you take a substr($str, $offset, $len), do you expect to always get exactly $len characters worth of substring?