wood burning stoves*
The moose likes Beginning Java and the fly likes Comparing two-character strings alphabetically. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Comparing two-character strings alphabetically." Watch "Comparing two-character strings alphabetically." New topic
Author

Comparing two-character strings alphabetically.

Adam Altmann
Greenhorn

Joined: Jun 08, 2005
Posts: 21
Disclaimer: I'm not sure if this belongs in Intermediate or Beginner, but I'm giving it a shot here. Please don't hurt me.

What I'm trying to accomplish is this:

I have to read in this field from a database, which is a two-character field that starts at "ZZ", and decrements "ZZ", "ZY", "ZX", "ZW", etc. I have to grab the last two ("ZX", and "ZW", for example) for any given group of records, and then use those codes to do further queries. (Think of them as representing days, and I'm needing to get info for the last two days.) So, to recap, out of a bunch of these ZZ - ?? codes, I need to find and use the "lowest" two.

I've managed to get it to work, more or less, by breaking the string apart using .charAt() and then using Character.valueOf(), and comparing the unicode, but it's ugly and I'm fairly certain that there has to be a better way that I'm overlooking.

Any suggestions?

Thanks in advance.
John Smith
Ranch Hand

Joined: Oct 08, 2001
Posts: 2937
Well, here is one solution: put the candidate Strings in the list, and sort it using the well defined Collections API. After the sorting, the last two Strings in the list will be what you want:


Output: [AA, AZ, BB, CC, ZY, ZZ]
[ June 09, 2005: Message edited by: John Smith ]
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Can your database query just order by this field?

Failing that, look at the compareTo() method. The List solution may well be the best today, but compareTo() is worth knowing, too.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Comparing two-character strings alphabetically.