Libraryless. Click here for Pure Java version (3123L/17K).
1 | // from https://introcs.cs.princeton.edu/java/31datatype/Soundex.java.html |
2 | |
3 | static S soundex(S s) { |
4 | if (empty(s)) ret ""; |
5 | char[] x = s.toUpperCase().toCharArray(); |
6 | char firstLetter = x[0]; |
7 | |
8 | // convert letters to numeric code |
9 | for (int i = 0; i < x.length; i++) { |
10 | switch (x[i]) { |
11 | |
12 | case 'B': |
13 | case 'F': |
14 | case 'P': |
15 | case 'V': |
16 | x[i] = '1'; |
17 | break; |
18 | |
19 | case 'C': |
20 | case 'G': |
21 | case 'J': |
22 | case 'K': |
23 | case 'Q': |
24 | case 'S': |
25 | case 'X': |
26 | case 'Z': |
27 | x[i] = '2'; |
28 | break; |
29 | |
30 | case 'D': |
31 | case 'T': |
32 | x[i] = '3'; |
33 | break; |
34 | |
35 | case 'L': |
36 | x[i] = '4'; |
37 | break; |
38 | |
39 | case 'M': |
40 | case 'N': |
41 | x[i] = '5'; |
42 | break; |
43 | |
44 | case 'R': |
45 | x[i] = '6'; |
46 | break; |
47 | |
48 | default: |
49 | x[i] = '0'; |
50 | break; |
51 | } |
52 | } |
53 | |
54 | // remove duplicates |
55 | new StringBuilder output; |
56 | output.append(firstLetter); |
57 | for (int i = 1; i < x.length; i++) |
58 | if (x[i] != x[i-1] && x[i] != '0') |
59 | output.append(x[i]); |
60 | |
61 | // pad with 0's or truncate |
62 | output.append("0000"); |
63 | return takeFirst(str(output), 4); |
64 | } |
download show line numbers debug dex old transpilations
Travelled to 3 computer(s): bhatertpkbcr, mqqgnosmbjvj, pyentgdyhuwx
No comments. add comment
Snippet ID: | #1031883 |
Snippet name: | soundex |
Eternal ID of this version: | #1031883/1 |
Text MD5: | e2a44de69600ed98ddfda4e84ac5445d |
Transpilation MD5: | eb4fff2d25cd183b6d8929177c500dd8 |
Author: | stefan |
Category: | javax |
Type: | JavaX fragment (include) |
Public (visible to everyone): | Yes |
Archived (hidden from active list): | No |
Created/modified: | 2021-07-24 01:31:15 |
Source code size: | 1369 bytes / 64 lines |
Pitched / IR pitched: | No / No |
Views / Downloads: | 158 / 224 |
Referenced in: | [show references] |