【问题标题】:Checking if a passcode contains enough special signs [ ! , % , & , ? , ...]检查密码是否包含足够的特殊符号 [ ! , % , & , ? , ...]
【发布时间】:2022-01-26 12:45:37
【问题描述】:

我为此创建了一个函数:

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;
    }
}

但正如您所见,它的效率并不高。有人知道更好的方法吗?

【问题讨论】:

  • 也许return (strchr("!?^&%", *x) != NULL);
  • 为什么x 是指针?
  • 您可以使用查找表,或者切换大小写。 (根据基准,if 最好在 4 次检查范围内切换)。更高效 - LUT,没有指针只是 char
  • SIGN_CHECKER 应该只检查字符串的第一个字符吗?
  • 你的函数错了。请出示调用SIGN_CHECKER的代码,然后我们可以告诉您更多错误原因。

标签: c char c-strings function-definition


【解决方案1】:

内存使用优化的典型执行速度是创建一个简单的查找表。

#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 机器码非常高效(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

【讨论】:

    【解决方案2】:

    对于初学者来说,声明具有char * 类型的函数参数没有意义,因为在函数中只检查了一个字符。

    函数可以通过以下方式声明和定义

    #include <string.h>
    
    //...
    
    int SIGN_CHECKER( char c )
    {
        return c != '\0' && strchr( "!?^&%", c );
    }
    

    如您所见,在函数中只写一行就足够了。

    【讨论】:

      【解决方案3】:

      您可以尝试使用正则表达式,如下所示:

      #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);
      }
      

      知道将字符串和正则表达式模式中的特殊符号传递给函数:

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

      从article 阅读更多关于如何在 c 中使用正则表达式的信息。

      【讨论】:

        猜你喜欢
        • 2010-12-20
        • 1970-01-01
        • 2012-10-05
        • 2016-08-24
        • 2022-11-14
        • 2016-08-01
        • 2014-11-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多