Soundex: Difference between revisions
Content deleted Content added
→{{header|Common Lisp}}: Only need three 0 chars. |
→{{header|C}}: Alternative implementation. |
||
Line 107: | Line 107: | ||
return 0; |
return 0; |
||
}</lang> |
|||
Non-obfuscated, sanely-written alternative: |
|||
<lang c>#include <stdio.h> |
|||
#include <stdlib.h> |
|||
#include <string.h> |
|||
#include <ctype.h> |
|||
#include <errno.h> |
|||
int get_code(int ch) |
|||
{ |
|||
if (strchr("BFPV", ch)) |
|||
return '1'; |
|||
if (strchr("CGJKQSXZ", ch)) |
|||
return '2'; |
|||
if (strchr("DT", ch)) |
|||
return '3'; |
|||
if (strchr("L", ch)) |
|||
return '4'; |
|||
if (strchr("MN", ch)) |
|||
return '5'; |
|||
if (strchr("R", ch)) |
|||
return '6'; |
|||
return 0; |
|||
} |
|||
int soundex(const char *s, char *buf, size_t size) |
|||
{ |
|||
int ch, chprev = 0, count; |
|||
buf[0] = 0; |
|||
if (!*s) |
|||
return 0; |
|||
if (size < 5) |
|||
return -1; |
|||
*buf++ = toupper(*s++); |
|||
strcpy(buf, "000"); |
|||
for (count = 0; ch = get_code(toupper(*s)), *s++ && count++ < 4; ) { |
|||
if (ch && ch != chprev) |
|||
*buf++ = ch; |
|||
chprev = ch; |
|||
} |
|||
return 0; |
|||
} |
|||
int main(int argc, char **argv) |
|||
{ |
|||
char sbuf[8]; |
|||
if (argc < 2) { |
|||
if (argv[0] != 0) |
|||
fprintf(stderr, "usage: %s <name>\n", argv[0]); |
|||
return EXIT_FAILURE; |
|||
} |
|||
if (soundex(argv[1], sbuf, sizeof sbuf)) { |
|||
fprintf(stderr, "soundex buffer too small\n"); |
|||
return EXIT_FAILURE; |
|||
} |
|||
puts(sbuf); |
|||
return 0; |
|||
}</lang> |
}</lang> |
||