什么是strncmp

核心提示strncmp函数为字符串比较函数,字符串大小的比较是以ASCII 码表上的顺序来决定,此顺序亦为字符的值。其函数声明为int strncmp ( const char * str1, const char * str2, size_t n

最佳答案:

strncmp函数为字符串比较函数,字符串大小的比较是以ASCII 码表上的顺序来决定,此顺序亦为字符的值。其函数声明为int strncmp ( const char * str1, const char * str2, size_t n );功能是把 str1 和 str2 进行比较,最多比较前 n 个字节,若str1与str2的前n个字符相同,则返回0;若s1大于s2,则返回大于0的值;若s1 小于s2,则返回小于0的值。

详情介绍

strncmp函数为字符串比较函数,字符串大小的比较是以ASCII 码表上的顺序来决定,此顺序亦为字符的值。其函数声明为int strncmp ( const char * str1, const char * str2, size_t n );功能是把 str1 和 str2 进行比较,最多比较前 n 个字节,若str1与str2的前n个字符相同,则返回0;若s1大于s2,则返回大于0的值;若s1 小于s2,则返回小于0的值。

中文名
strncmp
外文名
strncmp
作用
比较s1和s2字符串
应用
C语言
定义
指定比较size个字符
输出
负数、0、正数

strncmpstrncmp语法

strncmp函数声明

int strncmp(const char *str1, const char *str2, size_t n)

strncmp参数

str1-- 要进行比较的第一个字符串。

str2-- 要进行比较的第二个字符串。

n-- 要比较的最大字符数。

strncmp返回值

该函数返回值如下:

如果返回值 < 0,则表示 str1 小于 str2。

如果返回值 > 0,则表示 str2 小于 str1。

如果返回值 = 0,则表示 str1 等于 str2。

strncmp功能比较

函数 strncmp 与函数strcmp极为类似,但功能不完全相同,区别如下:

(1)strncmp函数

用来比较s1和s2字符串的前n个字符。如果两个字符串相等的话,strncmp将返回0。如果s1是s2的一个子串的话,s1小于s2。

(2)strcmp函数

同样用于比较两个字符串 ,设这两个字符串为str1,str2

若str1==str2,则返回零;

若str1 > str2,则返回正数;

若str1< str2,则返回负数。

即:两个字符串自左向右逐个字符相比(按ASCII值大小相比较),直到出现不同的字符或遇"0"为止。

(3)总结

两者不同之处是,strncmp函数是指定比较size个字符,strcmp函数比较整个字符,直到出现不同的字符或遇"0"为止。

strncmp应用示例

strncmp示例1

#include <cstring>#include <cstdio>int main(){    char *buf1="aaabbb",*buf2="bbbccc",*buf3="ccc";    int ptr;    ptr=strncmp(buf2,buf1,3);    if(ptr>0)        printf("buffer2 is greater than buffer1n");    else if(ptr<0)        printf("buffer2 is less than buffer1n");    ptr=strncmp(buf2,buf3,3);    if(ptr>0)        printf("buffer2 is greater than buffer3n");    else if(ptr<0)        printf("buffer2 is less than buffer3n");    return 0;}
ouput:buffer2 is greater than buffer1buffer2 is less than buffer3

strncmp示例 2

#include<stdio.h>#include<string.h>int main(){char str={"R2D2","C3PO","R2A6"};int n;puts("Looking for R2 as tromechdroids...");for(n=0;n<3;n++){if(strncmp(str,"R2xx",2)==0){printf("found%sn",str);}}return0;}
ouput:Looking for R2 as tromechdroids...foundR2D2foundR2A6

strncmp拓展延伸-PHP中strncmp

函数名: strncmp ()

功 能:比较字符串的前N个字符

用 法:

int strncmp(stringstr1,charstr2,intlen);

说明:比较字符串str1和str2的大小,如果str1小于str2,返回值就<0,反之如果str1大于str2,返回值就>0,如果str1等于str2,返回值就=0,len指的是str1与str2的比较的字符数。此函数功能即比较字符串str1和str2的前len个字符。

提示:该函数区分大小写。

示例:

<?php$str1="Ilikephp!";$str2="ianfine!";echo strncmp($str1,$str2,2);?>

结果为:-1

 
友情链接
鄂ICP备19019357号-22