Skip to content

Instantly share code, notes, and snippets.

@gwang
Created August 30, 2015 04:05
Show Gist options
  • Select an option

  • Save gwang/bc2c5f205b5b939cfe91 to your computer and use it in GitHub Desktop.

Select an option

Save gwang/bc2c5f205b5b939cfe91 to your computer and use it in GitHub Desktop.
find if there is any repeated character in a given ascii string
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
/* c implementation to test is an ASCII string has deplicated characters */
/**
* [main description]
* @param argc [number of argument]
* @param argv [argument values]
* @return [0 passed, 1 missed input, 2 failed]
*/
int main(int argc, char **argv)
{
unsigned int hash[8];
int i, j, k;
char *input;
if (argc < 2) {
printf("Usage: %s string\n", argv[0]);
exit(1);
}
input = argv[1];
printf("Testing %s ...\n", input);
for (i=0; i<8; i++) { hash[i] = 0; }
for (i=0; i<strlen(input); i++)
{
j = input[i] / 32; k = input[i] % 32;
// this is how we check if the bit was set to 1
if (hash[j] & (1<<k))
{
printf("There are more than one %c in the string.\n", input[i]);
exit(2);
}
// This is how you set the kth bit to 1;
hash[j] |= 1 << k;
// BTW, to clear a bit, number &= ~(1 << x)
// and to toggle a bit, number ^= 1 << x;
}
printf("No duplicating character found.\n");
return(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment