Home > Back-end >  Checking if a passcode contains enough special signs [ ! , % , & , ? , ...]
Checking if a passcode contains enough special signs [ ! , % , & , ? , ...]

Time:01-27

I did create a function for this:

int SIGN_CHECKER (char* x)
{
    if(*x == '!')
    {
        return 1;
    } else if(*x == '?')
    {
        return 1;
    } else if(*x == '^')
    {
        return 1;
    } else if(*x == '&')
    {
        return 1;
    } else if(*x == '%')
    {
        return 1;
    } else
    {
        return 0;
    }
}

But as u can see, its not that efficient, do anybody knows a better way? Thank u

CodePudding user response:

The typical execution speed over memory use optimization is to create a simple look-up table.

#include <stdbool.h>

int sign_checker (char x)
{
  static const bool is_special [256] = 
  {
    ['!'] = true,
    ['?'] = true,
    ['^'] = true,
    ['&'] = true,
    ['%'] = true,
  };

  return is_special [(unsigned char)x];
}

x86 machine code is very efficient (gcc -O3):

SIGN_CHECKER:
        movsx   rdi, dil
        movzx   eax, BYTE PTR is_special.0[rdi]
        ret
is_special.0:
        .zero   33
        .byte   1
        .zero   3
        .byte   1
        .byte   1
        .zero   24
        .byte   1
        .zero   30
        .byte   1
        .zero   161

CodePudding user response:

For starters the declaration of the function parameter having the type char * does not make a sense because only one character is checked within the function.

The function can be declared and defined the following way

#include <string.h>

//...

int SIGN_CHECKER( char c )
{
    return c != '\0' && strchr( "!?^&%", c );
}

As you can see it is enough to write just one line within the function.

CodePudding user response:

you can try using regular expression, something like this :

#include <regex.h>      
#include <stdio.h>  
#include <stdlib.h>
int check_pattern(char *string, char *pattern){
    regex_t regex;
    int res;

    // Compile regex
    res = regcomp(&regex, pattern, 0);
    
    // if there is error on compiling regex
    if (res)
        exit(1);

    // Execute regex
    res = regexec(&regex, string, 0, NULL, 0);
    if (!res) 
        return (1);
    else 
        return (0);

    // Free memory
    regfree(&regex);
}

know pass to the function the string and the special signs in regex pattern :

int main()
{
    // special signs are : "?*-"
    printf("%d\n", check_pattern("abc?d", "[?*-]"));
} 

read more about how to use regular expression in c from this article.

  •  Tags:  
  • Related