Given a word, I've to replace some specific alphabets with some specific letters such as 1 for a, 5 for b etc. I'm using regex for this. I understand that StringBuilder is the best way to deal with this problem as I'm doing a lot of string manipulations. Here is what I'm doing:
String word = "foobooandfoo"; String converted = ""; converted = word.replaceAll("[ao]", "1"); converted = converted.replaceAll("[df]", "2"); converted = converted.replaceAll("[n]", "3");
My problem is how to rewrite this program using StringBuilder. I tried everything but I can't succeed. Or using String is just fine for this?
I think this is a case where clarity and performance happily coincide. I would use a lookup table to do the "translation".
If you have a large alphabet for the
strinput, or your mappings are sparse, you could use a real map, like this:
While these implementations work in-place, you could create a new
StringBuilderinstance (or append to one that's passed in).