曲径通幽论坛

标题: strcmp() --- 比较两个字符串 [打印本页]

作者: beyes    时间: 2010-5-10 15:02
标题: strcmp() --- 比较两个字符串
函数原型
#include <string.h>
int strcmp(const char *s1, const char *s2);
说明:
该函数比较字符串 s1 和 s2,如果 s1 等于 s2 则函数返回 0;如果 s1 包含 s2,则返回大于0的数;如果 s1 小于 s2,则返回小于0的数。
字符串的大小比较是以 ASCII 表上的顺序来决定的,这个顺序也是字符的值。

举例:
#include <stdio.h>
#include <string.h>

int main ()
{
        const char *p = "hello world";
        const char *p1 = "hello";
        const char *p2 = "hello world";
        const char *p3 = "hello world32";

        int k;

        k = strcmp (p, p2);
        printf ("两字符串相等,返回值为 %d\n", k);

        k = strcmp (p, p1);
        printf ("字符串1大于字符串2,返回值为 %d\n", k);

        k = strcmp (p, p3);
        printf ("字符串1小于字符串2,返回值为 %d\n", k);

        return (0);
}
运行与输出
./strcmp
两字符串相等,返回值为 0
字符串1大于字符串2,返回值为 1
字符串1小于字符串2,返回值为 -1





欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2