. - , , :
1:
, "A" , "N" , "B" "X" - . , "SL5 3QW" "AANBNAA".
:
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);
}
:
public static void main(final String[] args){
System.out.println(map("SL5 3QW"));
}
:
AANBNAA
2:
e.g.2. , "œ" (x'9D '), "oe" (x'6F65 '), "ß" - "ss", "å" - "a" ..
:
, API Normalizer. . .
, , , , . , downvotes if/else. , / :
public interface CharTransformer{
boolean supports(char input);
char transform(char input);
}
, . , , . , . Transformer , .
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);
}
:
Note. Others suggested using a map. Although I don’t think a standard map is good for this task, you can use the Guava MapMaker.makeComputingMap (function) to calculate the substitutions as (and automatically cache them). This way you have a lazily initialized caching map.