Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

64
LINES

< > BotCompany Repo | #1031883 // soundex

JavaX fragment (include) [tags: use-pretranspiled]

Libraryless. Click here for Pure Java version (3123L/17K).

// from https://introcs.cs.princeton.edu/java/31datatype/Soundex.java.html

static S soundex(S s) { 
  if (empty(s)) ret "";
  char[] x = s.toUpperCase().toCharArray();
  char firstLetter = x[0];

  // convert letters to numeric code
  for (int i = 0; i < x.length; i++) {
      switch (x[i]) {

          case 'B':
          case 'F':
          case 'P':
          case 'V':
              x[i] = '1';
              break;

          case 'C':
          case 'G':
          case 'J':
          case 'K':
          case 'Q':
          case 'S':
          case 'X':
          case 'Z':
              x[i] = '2';
              break;

          case 'D':
          case 'T':
              x[i] = '3';
              break;

          case 'L':
              x[i] = '4';
              break;

          case 'M':
          case 'N':
              x[i] = '5';
              break;

          case 'R':
              x[i] = '6';
              break;

          default:
              x[i] = '0';
              break;
      }
  }

  // remove duplicates
  new StringBuilder output;
  output.append(firstLetter);
  for (int i = 1; i < x.length; i++)
      if (x[i] != x[i-1] && x[i] != '0')
          output.append(x[i]);

  // pad with 0's or truncate
  output.append("0000");
  return takeFirst(str(output), 4);
}

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: 157 / 223
Referenced in: [show references]