C语言函数学习之strncpy

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

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

include #include 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 #include 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 ~]#

comments powered by Disqus