C语言细节知识积累: strncpy

为了截取部分字符串,我们经常需要使用strncpy

如下面这段截取年、月、日的代码

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])

{
   char *sInput = "20110910";
   char sTmp[10] = "";

   strncpy(sTmp, sInput, 4);
   printf("Year: %s\r\n", sTmp);

   strncpy(sTmp, sInput+4, 2);
   printf("Month: %s\r\n", sTmp);

   strncpy(sTmp, sInput+6, 2);
   printf("Day: %s\r\n", sTmp);

   return 0;
}

但其运行结果却非常奇怪:

[root@localhost ~]# ./test
Year: 2011
Month: 0911
Day: 1011
[root@localhost ~]#

仔细分析,发现后两个字符就是year的后两个字符,查看strncpy的帮助,终于了解了:

strncpy为了便于进行字符串拼装,是不会在最后加\0的。

因此,代码需要如下修改

的代码

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])

{
   char *sInput = "20110910";
   char sTmp[10] = "";

   strncpy(sTmp, sInput, 4);
  
sTmp[4] = 0;
   printf("Year: %s\r\n", sTmp);

   strncpy(sTmp, sInput+4, 2);
  
sTmp[2] = 0;
   printf("Month: %s\r\n", sTmp);

   strncpy(sTmp, sInput+6, 2);
  
sTmp[2] = 0;
   printf("Day: %s\r\n", sTmp);

   return 0;
}

运行结果正确了:

[root@localhost ~]# ./test
Year: 2011
Month: 09
Day: 10
[root@localhost ~]#

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值