File tree Expand file tree Collapse file tree 1 file changed +78
-0
lines changed Expand file tree Collapse file tree 1 file changed +78
-0
lines changed Original file line number Diff line number Diff line change
1
+ package soundex ;
2
+
3
+ import java .util .Scanner ;
4
+
5
+ public class Soundex {
6
+
7
+ public static String soundex (String str ) {
8
+
9
+ char [] s = str .toUpperCase ().toCharArray ();
10
+ //retaining first letter
11
+ String output = s [0 ] + "" ;
12
+
13
+ //replacing consonants with digits
14
+ for (int i = 0 ; i <s .length ; i ++) {
15
+ switch (s [i ]) {
16
+ case 'B' :
17
+ case 'F' :
18
+ case 'P' :
19
+ case 'V' :
20
+ s [i ] = '1' ;
21
+ break ;
22
+
23
+ case 'C' :
24
+ case 'G' :
25
+ case 'J' :
26
+ case 'K' :
27
+ case 'Q' :
28
+ case 'S' :
29
+ case 'X' :
30
+ case 'Z' :
31
+ s [i ] = '2' ;
32
+ break ;
33
+
34
+ case 'D' :
35
+ case 'T' :
36
+ s [i ] = '3' ;
37
+ break ;
38
+
39
+ case 'L' :
40
+ s [i ] = '4' ;
41
+ break ;
42
+
43
+ case 'M' :
44
+ case 'N' :
45
+ s [i ] = '5' ;
46
+ break ;
47
+
48
+ case 'R' :
49
+ s [i ] = '6' ;
50
+ break ;
51
+
52
+ default :
53
+ s [i ] = '0' ;
54
+ break ;
55
+
56
+ }
57
+ }
58
+
59
+ // removing duplicates
60
+ for (int i = 1 ; i < s .length ; i ++) {
61
+ if (s [i ] != s [i -1 ] && s [i ] != '0' )
62
+ output += s [i ];
63
+ }
64
+
65
+ // right padding with zeroes or truncating
66
+ output = output + "0000" ;
67
+ return output .substring (0 , 4 );
68
+ }
69
+
70
+ public static void main (String [] args ) {
71
+
72
+ Scanner sc = new Scanner (System .in );
73
+ System .out .println ("Enter the string" );
74
+ String str = sc .nextLine ();
75
+ String str_output = soundex (str );
76
+ System .out .println (str_output );
77
+ }
78
+ }
You can’t perform that action at this time.
0 commit comments