C - 比较数字字符串

7

出于职业好奇心,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;
}

“比较”这个词具体指什么?你的例子只包含了==运算符,但没有<。请给出更多的例子。 - Roland Illig
6个回答

9

strcmp() 我认为是最好的选择,因为它不需要进行任何数字转换。但在这种情况下,您需要确保其中一个存储了仅包含数字字符的字符串。

另外,您可以对该字符串执行 memcmp() 操作。

编辑1

正如其他人指出的有关前导零的问题,您可以手动浏览前导零,并通过传递指向第一个非零数字的指针来调用strcmp()memcmp()

编辑2

以下代码说明了我的意思。 这仅适用于整数,而不适用于浮点数。

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

对于浮点数,小数点后的尾随零应该手动删除。或者整个过程都要手动完成。
编辑4:我还想让您查看此浮点代码。这将检测小数点前导零和小数点后尾随零。例如,00000000000001.10000000000000 和 1.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;
}

在使用前需要进行一些测试。


谢谢。这是我经常使用的方法,因为我非常依赖str*函数族。看起来这实际上是一种常态。好知道! - Valdogg21
@Valdogg21:看一下我更新的代码,现在可以根据您设定的协议比较浮点数。 - phoxis

4

str(n)cmp 是最快速、最安全的方法。


2
str(n)cmp 在整数字符串具有不同数量前导零的情况下会失败。 - JAB
1
@JAB:你是说字符串“002”和“0002”是一样的吗? - Chris Eberle
@cnicutar:你在说什么?我指的是这样一种情况,比如将1000100进行比较。因为strcmpstrncmp都会返回非零值,所以比较会失败,但实际想要的结果应该是0,表示相等。 - JAB
@Chris:不,我的意思是由字符串“002”和“0002”表示的数字是相同的。 - JAB
我以为你在想别的事情 :-) 实际上,我没有考虑前导零。 - cnicutar
显示剩余4条评论

0
假设您希望它们完全相同,strncmp将是最快且最安全的选择,因为它可以进行直接比较而不需要任何转换。通常认为它比strcmp更安全。
然而,如果您希望000相等,或者以其他略微不同的方式表示相同的数字,则需要使用atoi

4
atoi()函数已被strtol()所取代,不应在新代码中使用。 - Dietrich Epp

-1
你可以简单地使用以下代码:

if(strcmp("123","123") == 0)

{

  printf("The strings are equal");

}

否则

{

  printf("The strings are not equal.");

}

在我看来,它应该可以工作。


问者想要匹配字符串中表示的两个数字是否相等。 - phoxis

-1
我建议对于整数使用这种方式:
int strcmp_for_integers(char *aa, char *bb){
    char aa2[11] = "";
    char bb2[11] = "";
    int answer;

    sprintf(aa2, "%010d", atoi(aa));
    sprintf(bb2, "%010d", atoi(bb));
    answer = strcmp(aa2, bb2);

    return answer;
}

atoi已被弃用。 - Roland Illig

-1
在我看来,“最安全”的方法可能是将两个参数转换为整数,然后进行测试,这样你就可以避免潜在的前导零问题。尽管如此,它可能不是最快或最有效的方法。

1
要正确地执行此操作,您需要一个任意大小的整数类型,这在标准C中不可用。 - Roland Illig

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接