遵循规范

POSIX.1-2001,POSIX.1-2008,C89,C99,SVr4、4.3BSD。

另外参见

bcmp(3),memcmp(3),strcasecmp(3),strcoll(3),字符串(3),strncasecmp(3),strverscmp(3),wcscmp(3),wcsncmp(3),ascii(7)

返回值

如果发现s1(或其前n个字节)分别小于,匹配或大于s2,则strcmp()和strncmp()函数将返回小于,等于或大于零的整数。 。

STRCMP - Linux手册页

Linux程序员手册 第3部分
更新日期: 2020-04-11

出版信息

这个页面是Linux手册页项目5.08版的一部分。有关项目的说明、有关报告错误的信息以及此页面的最新版本,请访问https://www.kernel.org/doc/man-pages/

名称

strcmp,strncmp-比较两个字符串

备注

POSIX.1仅指定:

非零返回值的符号应由比较的字符串中不同的第一对字节值(均被解释为无符号字符类型)之间的差的符号确定。

与大多数其他实现一样,在glibc中,返回值是从s1中的最后比较字节中减去s2中的最后比较字节的算术结果。 (如果两个字符相等,则此差为0。)

示例

下面的程序可用于演示strcmp()(给定两个参数时)和strncmp()(给定三个参数时)的操作。首先,使用strcmp()的一些示例:

$ ./string_comp ABC ABC
<str1> and <str2> are equal
$ ./string_comp ABC AB      # aqCaq is ASCII 67; aqCaq - aq aq = 67
<str1> is greater than <str2> (67)
$ ./string_comp ABA ABZ     # aqAaq is ASCII 65; aqZaq is ASCII 90
<str1> is less than <str2> (-25)
$ ./string_comp ABJ ABC
<str1> is greater than <str2> (7)
$ ./string_comp $aq1aq A   # 0201 - 0101 = 0100 (or 64 decimal)
<str1> is greater than <str2> (64)

最后一个示例使用bash(1)特定的语法来生成包含8位ASCII代码的字符串。结果表明,字符串比较使用无符号字符。

然后使用strncmp()的一些示例:

$ ./string_comp ABC AB 3
<str1> is greater than <str2> (67)
$ ./string_comp ABC AB 2
<str1> and <str2> are equal in the first 2 bytes

Program source

/* string_comp.c

   Licensed under GNU General Public License v2 or later.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int
main(int argc, char *argv[])
{
    int res;

    if (argc < 3) {
        fprintf(stderr, "Usage: %s <str1> <str2> [<len>]\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    if (argc == 3)
        res = strcmp(argv[1], argv[2]);
    else
        res = strncmp(argv[1], argv[2], atoi(argv[3]));

    if (res == 0) {
        printf("<str1> and <str2> are equal");
        if (argc > 3)
            printf(" in the first %d bytes\n", atoi(argv[3]));
        printf("\n");
    } else if (res < 0) {
        printf("<str1> is less than <str2> (%d)\n", res);
    } else {
        printf("<str1> is greater than <str2> (%d)\n", res);
    }

    exit(EXIT_SUCCESS);
}

说明

strcmp()函数比较两个字符串s1和s2。不考虑语言环境(有关语言环境的比较,请参阅strcoll(3))。使用无符号字符进行比较。

strcmp()返回表示比较结果的整数,如下所示:

*
如果s1和s2相等,则为0;否则为0。
*
如果s1小于s2,则为负值;
*
如果s1大于s2,则为正值。

除了仅比较s1和s2的前n个字节(最多),strncmp()函数相似。

语法

#include <string.h>

int strcmp(const char *s1, const char *s2);

int strncmp(const char *s1, const char *s2, size_t n);

属性

有关本节中使用的术语的说明,请参见attribute(7)。

InterfaceAttributeValue
strcmp(),strncmp()Thread safetyMT-Safe
日期:2019-08-20 18:01:25 来源:oir作者:oir