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!
Joined: Sep 25, 2003
Thanks very much for all of your replys! I will try some of this code later.... Jason
Joined: May 05, 2000
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.