<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.11</version>
</dependency>
Base64 codec = new Base64();
String original = "中文";
byte[] encoded = codec.encode(original.getBytes("UTF-8"));
String encodedStr = new String(encoded); // 5bCP5piO
byte[] decoded = codec.decode(encoded);
String decodedStr = new String(decoded, "UTF-8"); // 中文
System.out.println("編碼前: " + original);
System.out.println("編碼後: " + encodedStr);
System.out.println("解碼後: " + decodedStr);
Hex codec = new Hex();
String original = "中文";
char[] encoded = codec.encodeHex(original.getBytes("UTF-8"));
String encodedStr = new String(encoded); // e4b8ade69687
byte[] decoded = codec.decodeHex(encoded);
String decodedStr = new String(decoded, "UTF-8"); // 中文
System.out.println("編碼前: " + original);
System.out.println("編碼後: " + encodedStr);
System.out.println("解碼後: " + decodedStr);
Metaphone metaphone = new Metaphone();
RefinedSoundex refined = new RefinedSoundex();
Soundex soundex = new Soundex();
String[] words = {"resume", "resin"};
for (String w : words) {
System.out.println("Original: " + w);
System.out.println("Metaphone: " + metaphone.encode(w)); // RS / RSN
System.out.println("RefinedSoundex: " + refined.encode(w)); // R250 / R250
System.out.println("Soundex: " + soundex.encode(w)); // R250 / R250
System.out.println();
}
| 算法 | 輸出長度 | 精度 | 典型應用 |
|---|---|---|---|
| Soundex | 固定 4 碼 (字母+3數字) | 較低 | 姓名檢索、簡單去重 |
| RefinedSoundex | 可變長度 | 中等 | 改進版 Soundex |
| Metaphone | 可變長度 | 最高 (英語) | 拼寫糾錯、語音搜索、MP3 標籤匹配 |
Metaphone 為同音詞生成相同鍵值,比 Soundex 準確,但無固定長度。選型視業務容錯率而定。