曲径通幽论坛

标题: strncmp() -- 最多比较 n 个字符 [打印本页]

作者: beyes    时间: 2011-1-23 09:08
标题: strncmp() -- 最多比较 n 个字符
原型
#include <string.h>
int strncmp(const char *s1, const char *s2, size_t n);

说明:该函数最多比较 s1 和 s2 中的前 n 个字符。返回值结果为:

1. 如果 s1 中的前 n 个字符都和 s2 中的匹配,那么返回值为 0 。

2. 如果 s1 中的前 n 个字符里只要出现第一个不同于 s2 中的字符,且此字符的 ASCII 码大于 s2 中相应的 ASCII 码,则返回值大于 0。

3. 如果 s1 中的前 n 个字符里只要出现第一个不同于 s2 中的字符,且此字符的 ASCII 码小于 s2 中相应的 ASCII 码,则返回值小于 0 。

4. s1 的长度如果小于 n ,而又能在 s2 中匹配,那么返回值小于 0 。

5. 另外,不管  s1 有多长,只要前 n 个字符和 s2 中相匹配,那么返回值为 0 。


示例代码
#include <stdio.h>
#include <string.h>

int main()
{
         char s1[100];
         const char *s2 = "hello world";
         int len;

         printf ("input a string:");
         fgets (s1, 100, stdin);

         len = strncmp (s1, s2, 5);

         if (!len) {
                 printf ("Full match!\n");
                 return (0);
         }
         if ( len > 0) {
                 printf ("s1 > s2\n");
                 return (1);
         }
         printf ("s1 < s2\n");
         return (2);
}
运行输出
1. 全匹配情况
# ./strncmp
input a string:hello
Full match!
# ./strncmp
input a string:hellow
Full match!
2. 返回值大于零的情况:
# ./strncmp
input a string:hellp
s1 > s2
# ./strncmp
input a string:hez
s1 > s2
# ./strncmp
input a string:z
s1 > s2
3.返回值小于零的情况:
# ./strncmp
input a string:he
s1 < s2
# ./strncmp
input a string:helln
s1 < s2
# ./strncmp
input a string:a
s1 < s2

实现代码参考:
/**
* strncmp - Compare two length-limited strings
* @cs: One string
* @ct: Another string
* @count: The maximum number of bytes to compare
*/
int strncmp(const char * cs,const char * ct,size_t count)
{
     register signed char __res = 0;

     while (count) {
         if ((__res = *cs - *ct++) != 0 || !*cs++)
             break;
         count--;
     }

     return __res;
}





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