There are different ways to answer this question. The easiest way is probably to come up with answers for each of the problems individually:
Problem 1:
e.g.1 I want to map a string with "A"
for alphabetic characters, "N" for
numeric characters, "B" for space
characters and "X" for anything else.
Thus "SL5 3QW" becomes "AANBNAA".
Simple solution:
public static String map(final String input){
final char[] out = new char[input.length()];
for(int i = 0; i < input.length(); i++){
final char c = input.charAt(i);
final char t;
if(Character.isDigit(c)){
t = 'N';
} else if(Character.isWhitespace(c)){
t = 'B';
} else if(Character.isLetter(c)){
t = 'A';
} else{
t = 'X';
}
out[i] = t;
}
return new String(out);
}
Test:
public static void main(final String[] args){
System.out.println(map("SL5 3QW"));
}
Output:
AANBNAA
Problem 2:
e.g.2. I want to translate some
characters, such as "œ" (x'9D') to
"oe" (x'6F65'), "ß" to "ss", "å" to
"a", etc.
Solution:
This is standard functionality, you should use the Normalizer API for this. See these previous answers for reference.
The Big Picture
But on second thought there is of course a more general solution to your problem. Let's see how many downvotes I get for this one by the if/else lovers. Define an interface of a transformer that accepts certain characters and / or character classes and maps them to other characters:
public interface CharTransformer{
boolean supports(char input);
char transform(char input);
}
And now define a method that you can call with a string and a collection of such transformers. For every single character, each transformer will be queried to see if he supports this character. If he does, let him do the transformation. If no Transformer is found for a character, throw an exception.
public static String mapWithTransformers(final String input,
final Collection<? extends CharTransformer> transformers){
final char[] out = new char[input.length()];
for(int i = 0; i < input.length(); i++){
final char c = input.charAt(i);
char t = 0;
boolean matched = false;
for(final CharTransformer tr : transformers){
if(tr.supports(c)){
matched = true;
t = tr.transform(c);
break;
}
}
if(!matched){
throw new IllegalArgumentException("Found no Transformer for char: "
+ c);
}
out[i] = t;
}
return new String(out);
}
One more thing: Maps
Note: Others have suggested using a Map. While I don't think a standard map is good for this task, you could use Guava's MapMaker.makeComputingMap(function) to calculate the replacements as needed (and automatically cache them). That way you have a lazily initialized caching map.