一、单纯的字符串拷贝
#define SIZE 40
#define LIM 5
int main()
{
char qwords[LIM][SIZE];
char temp[SIZE];
int i = 0; //行统计
printf("Enter %d words beginning with q:\n", LIM);
while(i < LIM && s_gets(temp, SIZE))
{
/*
if(temp[0] != 'q') //判断temp第一个字符是否是以q开头,不以q开头,提示后重新输入。
//temp字符串和“q”的每1个元素是否相等。不相等,strncmp返回非0,提示扣重新输入。
相等,strncmp返回0,才会执行strcpy,i递增;
只有以q开头的字符串,才会执行strcpy,i递增。
*/
if (strncmp(temp, "q", 1) != 0)
{
printf("%s doesn't begin with q!\n", temp);
}
else//数组第一个字符相同,为q
{
strcpy(qwords[i], temp);
i++;
}
}
puts("Here are the words accetped:");
for (i = 0; i < LIM; i++)
{
puts(qwords[i]);
}
return 0;
}
第二种用法理解
strcpy
返回类型是char *
类型,用一个指针变量,可以接受其返回的现在地址信息
#include <stdio.h>
#include <string.h>
#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);
//strcpy返回类型是char *类型,用一个指针变量,可以接受其返回的现在地址信息
ps = strcpy(copy + 7, orig);
//strcpy()把源字符串orig中的空字符也拷贝在内,在该例中,空字符覆盖了copy数组中that的第1上t
puts(copy);
//ps指向copy中的第8个元素(下标为7),因此puts(ps)从该处开始打印字符串
puts(ps);
return 0;
}