字符串比较--strcasecmp()和strncasecmp()

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow

也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!

               

函数说明 strcasecmp()用来比较参数s1和s2字符串,比较时会自动忽略大小写的差异。

返回值    若参数s1和s2字符串相同则返回0。s1长度大于s2长度则返回大于0 的值,s1 长度若小于s2 长度则返回小于0的值.

首先给出这两个函数的具体实现:

47 /*****************************************************************************/ 48 /* STRCASECMP() - Case-insensitive strcmp.                                   */ 49 /*****************************************************************************/ 50 static int strcasecmp(const char* s1, const char* s2) 51 52    char c1, c2; 53    do { c1 = *s1++; c2 = *s2++; } 54    while (c1 && c2 && (tolower(c1) == tolower(c2))); 55  56    return tolower(c1) - tolower(c2); 5758  59 /*****************************************************************************/ 60 /* STRNCASECMP() - Case-insensitive strncmp.                                 */ 61 /*****************************************************************************/ 62 static int strncasecmp(const char* s1, const char* s2, size_t n) 63 64    char c1, c2; 65  66    if (!n) return 067  68    do { c1 = *s1++; c2 = *s2++; } 69    while (--n && c1 && c2 && (tolower(c1) == tolower(c2))); 70  71    return tolower(c1) - tolower(c2); 72 }


  1. #include <stdio.h>  
  2. #include <string.h>  
  3. #include <ctype.h>  
  4. int strcasecmp(const char *s1, const char *s2)  
  5. {  
  6.     int c1, c2;  
  7.     do {  
  8.         c1 = tolower(*s1++);  
  9.         c2 = tolower(*s2++);  
  10.     } while(c1 == c2 && c1 != 0);  
  11.     return c1 - c2;  
  12. }  
  13. int main(void)  
  14. {  
  15.     int n = 4;  
  16.     char str1[] = "Acef";  
  17.     char str2[] = "ACEFd";  
  18.     printf("strcasecmp(str1, str2) = %d/n", strcasecmp(str1, str2));  
  19.     return 0;  
  20. }  
扫描二维码关注公众号,回复: 5010978 查看本文章

函数说明:strncasecmp()用来比较参数s1和s2字符串前n个字符,比较时会自动忽略大小写的差异

返回值   :若参数s1和s2字符串相同则返回0 s1若大于s2则返回大于0的值 s1若小于s2则返回小于0的值

[c-sharp] view plain copy
  1. #include <stdio.h>  
  2. #include <string.h>  
  3. #include <ctype.h>  
  4.   
  5. int mystrncasecmp(const char *s1, const char *s2, int n)  
  6. {  
  7.     int c1, c2;  
  8.     do {  
  9.         c1 = tolower(*s1++);  
  10.         c2 = tolower(*s2++);  
  11.     } while((--n > 0) && c1 == c2 && c1 != 0);  
  12.     return c1 - c2;  
  13. }  
  14. int main(void)  
  15. {  
  16.     int n = 4;  
  17.     char str3[] = "ABCf";  
  18.     char str4[] = "abcd";  
  19.     printf("mystrncasecmp(str3, str4, n) = %d/n", mystrncasecmp(str3, str4, n));  
  20.     return 0;  

           

给我老师的人工智能教程打call!http://blog.csdn.net/jiangjunshow

这里写图片描述

猜你喜欢

转载自blog.csdn.net/hfhhgfv/article/details/84101256