本文摘录自C Primer Plus第305页。
一、strcpy()的高级属性
strcpy()函数还有另外两个有用的属性。首先,它是char*类型,它返回的是第一个参数的值,即一个字符的地址;其次,第一个参数不需要指向数组的开始,这样就可以只复制数组的一部分。下面举例说明:
#include <stdio.h>
#include <string.h> /* declares strcpy() */
#define WORDS "beast"
#define SIZE 40
int main(void)
{
const char * orig = WORDS;
char copy[SIZE] = "Be the best that you can be.";
char * ps;
puts(orig);
puts(copy);
ps = strcpy(copy + 7, orig);
puts(copy);
puts(ps);
return 0;
}
输出如下:
beast
Be the best that you can be.
Be the beast
beast
注意,strcpy()从源字符串复制空字符。在这个例子中,空字符覆盖了that中的第一个t,这样新的字符串就以beast结尾。还要注意,ps指向copy的第8个元素,这是因为第一个参数是copy+7。因此,puts(ps)从这个地方就开始输出字符串。
二、strncpy()函数
下面是一个条用strncpy()函数的例子:
/* copy3.c -- strncpy() demo */
#include <stdio.h>
#include <string.h> /* declares strncpy() */
#define SIZE 40
#define TARGSIZE 7
#define LIM 5
int main(void)
{
char qwords[LIM][TARGSIZE];
char temp[SIZE];
int i = 0;
printf("Enter %d words beginning with q:\n", LIM);
while (i < LIM && gets(temp))
{
if (temp[0] != 'q')
printf("%s doesn't begin with q!\n", temp);
else
{
strncpy(qwords[i], temp, TARGSIZE - 1);
qwords[i][TARGSIZE - 1] = '\0';
i++;
}
}
puts("Here are the words accepted:");
for (i = 0; i < LIM; i++)
puts(qwords[i]);
return 0;
}
下面是一个运行实例:
Enter 5 words beginning with q:
quack
quadratic
quisling
quota
quagga
Here are the words accepted:
quack
quadra
quisli
quota
quagga
函数调用strncpy(target,source.n)从source把n个字符(或空字符之前的字符,这两种最先满足的那个决定何时终止)复制到target。因此,如果源字符串的字符数比n小,整个字符串都被复制过来,包括空字符。函数复制的字符数绝不会超过n,因此如果源字符串还没结束就达到了限制,就不会添加空字符。结果,最终的字符串可能有也可能没有空字符。出于这个原因,程序设置的n比目标数组的大小要少1,这样就可以把空字符放到数组的最后一个元素里。
strncpy(qwords[i], temp, TARGSIZE - 1);
qwords[i][TARGSIZE - 1] = '\0'; //注意这里,没有结束'\0\'可能会乱码
这就确保您已经存储了一个字符串。如果源字符串确实可以容纳得下,和它一起复制的空字符就标志着字符串的真正结束。如果源字符串在目标数组中容纳不下,这个最后的空字符就标志着字符串的结束。