strncmp函数——比较特定长度的字符串

本文详细介绍了C/C++中strncmp函数的用法,包括其语法、参数说明及返回值。通过具体示例展示了如何使用strncmp函数比较指定长度的字符串,帮助读者深入理解并掌握这一字符串操作函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转自:https://blog.youkuaiyun.com/dongzhe8/article/details/50576307

strncmp函数用于比较特定长度的字符串。

头文件:string.h。

语法  int strncmp(const char *string1,   const char *string2,   size_t count);
 
strncmp函数的语法参数说明如表2.4所示。

表2.4  参数说明

参数描述
string1 给定的字符串
string2 给定的字符串
count 要进行比较的长度

返回值:当string1大于string2时,返回1;等于时,返回0;小于时,返回-1。

示例  本示例使用strncmp函数比较指定长度的字符串。
int main()
{
  char str1[]="Hello",str2[]="Help",str3[]="Hello";
  int a,b,c;
  a = strncmp(str1,str2,3);    //比较字符串str1,str2前3个字符
  b = strncmp(str2,str3,4);     //比较字符串str2,str3前4个字符
  c = strncmp(str1,str2,4);     //比较字符串str1,str2前4个字符
  cout<<a<<"\t"<<b<<"\t"<<c<<"\n";
}

运行结果:

0 1 -1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值