C - 比较数字字符串

标签 c strcmp atoi strtol

出于专业的好奇心,在 C 中比较两个全数字字符串的最安全/最快/最有效的方法是什么?

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void){

char str1[5] = "123";
char str2[5] = "123";
char *ptr;

if(atoi(str1) == atoi(str2))
    printf("Equal strings");

if(strtol(str1,&ptr,10) == strtol(str2,&ptr,10))
    printf("Equal strings");

if(strcmp(str1,str2)==0)
    printf("Equal strings");

return 0;
}

最佳答案

strcmp () 在我看来,因为它不需要任何数字转换。但在这种情况下,您需要确保其中一个存储仅包含数字字符的字符串。

你也可以在字符串上做memcmp()

编辑1

正如其他人关于前导零所指出的那样,您可以手动扫描前导零并通过传递指向第一个非零数字。

EDIT2

下面的代码告诉了我想说的。这仅适用于整数,不适用于 float 。

int main (void)
{
  char s1[128], s2[128];
  char *p1 = s1, *p2 = s2;

  /* populate s1, s2 */

  while (*p1 && (*p1 == '0'))
    p1++;

  while (*p2 && (*p2 == '0'))
    p2++;

  if (strcmp (p1, p2) == 0)
    printf ("\nEqual");
  else
    printf ("\nNot equal");

  printf ("\n");
  return 0;
}

对于 float ,应手动切掉小数点后的尾随零。

或者手动完成所有操作。

EDIT4

我还希望您看一下这段浮点代码。这将检测小数点前的前导零和小数点后的尾随零。例如

00000000000001.100000000000001.1 对于以下代码将相等

int main (void)
{
  char s1[128], s2[128];
  char *p1, *p2, *p1b, *p2b;

  printf ("\nEnter 1: ");
  scanf ("%s", s1);
  printf ("\nEnter 2: ");
  scanf ("%s", s2);

  p1 = s1;
  p2 = s2;
  /* used for counting backwards to trim trailing zeros
   * in case of floating point
   */
  p1b = s1 + strlen (s1) - 1;
  p2b = s2 + strlen (s2) - 1;


  /* Eliminate Leading Zeros */
  while (*p1 && (*p1 == '0'))
    p1++;

  while (*p2 && (*p2 == '0'))
    p2++;

  /* Match upto decimal point */
  while (((*p1 && *p2) && ((*p1 != '.') && (*p2 != '.'))) && (*p1 == *p2))
  {
    p1++;
    p2++;
  }

  /* if a decimal point was found, then eliminate trailing zeros */
  if ((*p1 == '.') && (*p2 == '.'))
  {
    /* Eliminate trailing zeros (from back) */
    while (*p1b == '0')
      p1b--;
    while (*p2b == '0')
      p2b--;

    /* match string forward, only upto the remaining portion after
     * discarding of the trailing zero after decimal
     */
    while (((p1 != p1b) && (p2 != p2b)) && (*p1 == *p2))
    {
      p1++;
      p2++;
    }
  }

  /* First condition on the LHS of || will be true for decimal portion
   * for float the RHS will be . If not equal then none will be equal
   */
  if (((*p1 == '\0') && (*p2 == '\0')) ||  ((p1 == p1b) && (p2 == p2b)))
    printf ("\nEqual");
  else
    printf ("\nNot equal");

  printf ("\n");
  return 0;
}

使用前需要一些测试。

关于C - 比较数字字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6389919/

相关文章:

c - 如何正确比较 C 中的字符串?

没有参数的 c optarg atoi

c - 在 C 中使用用户输入运行外部命令

iphone - 在 UITableView 中插入新单元格时表格未向上移动

C++ 在模板特化中的 strcmp() 中从 'char' 到 'const char*' 的无效转换

arrays - 在 C 中从 stdin 获取数字到数组

c++ - C++ 中 "atoi"函数的简单示例

c - printf 定义中的 __format 到底意味着什么?

c - 具有指针转换的局部变量

c - strcmp 有什么问题?