曲径通幽论坛

 找回密码
 立即注册
搜索
查看: 5247|回复: 0
打印 上一主题 下一主题

[字符串] strncmp() -- 最多比较 n 个字符

[复制链接]

4918

主题

5880

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34395
跳转到指定楼层
楼主
发表于 2011-1-23 09:08:31 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
原型
#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;
}
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|曲径通幽 ( 琼ICP备11001422号-1|公安备案:46900502000207 )

GMT+8, 2025-5-6 17:09 , Processed in 0.061237 second(s), 22 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表