【string總結之四】C語言strcmp/strncmp

C語言string的幾個函數雖然比較簡單, 但是還是想總結在這裏, 以免每次用到都要去查一下

strtol,strstr,strcat/strncat,strcpy/strncpy,strcmp/strncmp

1.strcmp

【頭文件與函數原型】

#include <string.h>

int strcmp(const char *s1, const char *s2);

【函數功能】(注意這裏的返回值用等於,大於,小於0去區分,不要用-1與1去區分,可加打印看出有些返回值不是-1或1)

The  strcmp() function compares the two strings s1 and s2.  It returns an integer less than, equal to, or greater than zero if s1 is found, respectively, to be less than, to match, or be greater than s2.

strcmp沒什麼好說的,核心就是s1,s2比較出大小爲止,其中字符串結尾標誌'\0'也要參加比較

2.strncmp

【頭文件與函數原型】

#include <string.h>

int strncmp(const char *s1, const char *s2, size_t n);

【函數功能】

The strncmp() function is similar, except it only compares the first (at most) n characters of s1 and s2.

【注意】

strncmp的返回值與strcmp的返回值一致,但是strncmp最多比較s1,s2的前n個字節,那麼若n的長度超過s1或s2,那就與strcmp一樣,比出結果爲止,這時比較的就沒有n個字節,體現most的意義

root@ubuntu:/lianxi/lianxi_oj/string# gcc strncmp.c
root@ubuntu:/lianxi/lianxi_oj/string# ./a.out
=====TEST CASE01=====
TEST CASE01, ret = 0

=====TEST CASE02=====
TEST CASE02, ret = -1

root@ubuntu:/lianxi/lianxi_oj/string# 
  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 #include <string.h>
  4 int main(int argc, char* argv[])
  5 {   
  6     int ret = 0;
  7     printf("=====TEST CASE01=====\n");
  8     char* s1 = "hello";//h e l l o \0
  9     char* s2 = "helloworld";//h e l l o w o r l d \0
 10     ret = strncmp(s1, s2, 5);
 11     printf("TEST CASE01, ret = %d\n", ret);//ret == 0
 12     putchar(10);
 13     
 14     printf("=====TEST CASE02=====\n");
 15     ret = strncmp(s1, s2, strlen(s2));
 16     printf("TEST CASE02, ret = %d\n", ret);//ret < 0
 17     putchar(10);
 18     
 19     return 0;
 20 }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章