Stories
Slash Boxes
Comments
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

jdavidb (1361)

jdavidb
  (email not shown publicly)
http://voiceofjohn.blogspot.com/

J. David Blackstone has a Bachelor of Science in Computer Science and Engineering and nine years of experience at a wireless telecommunications company, where he learned Perl and never looked back. J. David has an advantage in that he works really hard, he has a passion for writing good software, and he knows many of the world's best Perl programmers.

Journal of jdavidb (1361)

Friday January 25, 2008
03:12 PM

Java brain damage of the day: substr

[ #35489 ]

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."

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
 Full
 Abbreviated
 Hidden
More | Login | Reply
Loading... please wait.
  • 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 dun
    • 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?