Is there a more compact way to do this?? Thanks for any help! Jason
Joel McNary
Bartender
Joined: Aug 20, 2001
Posts: 1815
posted
0
Yes, that is bulky. What you might want to do is set up a Hash to handle this for you. Also, you can use regualr expressions to slim down the code a bit.
This print out 666-4242.
Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
Ernest Friedman-Hill
author and iconoclast
Marshal
Hi Jason, Welcome to JavaRanch! Wow. Yeah, that's not the most efficient way to do things, because each "replace" is allocating a whole new string and copying all the data over. I'd do this using a lookup table, since the translation is slightly irregular, something like
I'd test this code thoroughly before using it, as I just made it up off the top of my head. Note I used the explicit less-than/greater-than tests instead of Character.isLetter() so that non-ASCII letters simply wouldn't be converted; you might want to detect these and throw an exception of something.
Yep, you're sure right. See, I said to test very carefully!
jason candelora
Greenhorn
Joined: Sep 25, 2003
Posts: 16
posted
0
Thanks very much for all of your replys! I will try some of this code later.... Jason
Thomas Paul
mister krabs
Ranch Hand
Joined: May 05, 2000
Posts: 13974
posted
0
Originally posted by Ernest Friedman-Hill: Wow. Yeah, that's not the most efficient way to do things, because each "replace" is allocating a whole new string and copying all the data over.
Thankfully, it isn't quite as bad as that! If nothing is replaced then the original String is returned and no new String is created. So at worst we are creating six extra Strings that we didn't need. You will get no argument from me as to the inefficiency of running all those replace methods though! Another way to do it would be to convert the String into a char array and then use a switch statement to change the characters. No specific advantage to this. Just one more way to do the same thing.
Perhaps my solution is not as effecient, however... Just submitted a class TelephoneNumber to do phone formating to SourceForge http://sourceforge.net/snippet/detail.php?type=snippet&id=101225 The TelephoneNumber class represents a US telephone number. This class contains many constructors for various uses. It then stores the telephone number internally in seperate codes (area code, exchange, etc.). This encourages use of the format method to output the telephone number in any style the programmer wishes. [needs i18n work] Example usage: long number = 8005551212L; TelephoneNumber phone = new TelephoneNumber(number); StringBuffermsg = new StringBuffer("Call me at "); msg.append(phone.format()); // msg is now "Call me at (800) 555-1212"
David Koontz
Greenhorn
Joined: Oct 08, 2003
Posts: 14
posted
0
Oh - it handles this: n = new TelephoneNumber("(888) HOLY COW"); out.println(n.format()); prints the #s or alpha & #s David