[技术手册] 字符串比较函数

[复制链接]
23|0

头文件:#include<string.h>

函数声明:int strcmp(const char *s1,const char*s2);

函数说明:比较s1和s2指向的字符串的大小。

比较的方法:逐个字符去比较ascII码,一旦比较出大小返回。如果所有字符都一样,则返回0。

返回值:如果s1指向的字符串大于s2指向的字符串返回1,如果s1指向的字符串小于s2指向的字符串返回-1,如果相等的话返回0

函数声明: int strncmp(const char* s1,const char* s2, size_t n);

函数说明:比较s1和s2指向的字符串中的前n个字符

  1. #pragma warning(disable:4996)
  2. #define _CRT_SECURE_NO_WARNINGS
  3. #include<stdio.h>
  4. #include <string.h>

  5. int main()
  6. {
  7.         char* str1 = "helloworld";
  8.         char* str2 = "hellokitty";
  9.         if (strcmp(str1, str2) == 0)
  10.         {
  11.                 printf("str1==str2\n");
  12.         }
  13.         else if(strcmp(str1, str2) > 0)
  14.         {
  15.                 printf("str1>str2\n");
  16.         }
  17.         else
  18.         {
  19.                 printf("str1<str2\n");
  20.         }

  21.         if (strncmp(str1, str2, 5) == 0)
  22.         {
  23.                 printf("str1==str2\n");
  24.         }
  25.         else if(strncmp(str1, str2, 5) > 0)
  26.         {
  27.                 printf("str1>str2\n");
  28.         }
  29.         else
  30.         {
  31.                 printf("str1<str2\n");
  32.         }

  33.         return 0;
  34. }


————————————————
版权声明:本文为CSDN博主「害恶细君」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_50216991/article/details/141871740

您需要登录后才可以回帖 登录 | 注册

本版积分规则

277

主题

2435

帖子

3

粉丝
快速回复 在线客服 返回列表 返回顶部