C语言 strcpy()函数

来源:这里教程网 时间:2026-02-16 12:54:00 作者:

strcpy()函数将一个字符串复制到另一个字符串。

C strcpy()函数声明

char *strcpy(char *str1, const char *str2)

str1 – 这是复制其他字符串str2的值的目标字符串。函数的第一个参数。
str2 – 这是源字符串,该字符串的值被复制到目标字符串。这是函数的第二个参数。

strcpy()的返回值

此函数返回指向目标字符串的指针,或者您可以说它返回目标字符串str1。

示例:strcpy()函数

#include <stdio.h>#include <string.h>int main () {   char str1[20];   char str2[20];   //copying the string "Apple" to the str1   strcpy(str1, "Apple");   printf("String str1: %s\n", str1);   //copying the string "Banana" to the str2   strcpy(str2, "Banana");   printf("String str2: %s\n", str2);   //copying the value of str2 to the string str1   strcpy(str1, str2);    printf("String str1: %s\n", str1);   return 0;}

输出:

String str1: AppleString str2: BananaString str1: Banana

正如我在帖子的开头所提到的,这个函数返回指向目标字符串的指针,这意味着如果我们显示函数的返回值,它应该在将源字符串复制到目标字符串后显示目标字符串的值。让我们举一个例子来理解这一点。

#include <stdio.h>#include <string.h>int main () {   char str[20];   /* copying the string "Apple" to the str and    * displaying the return value of strcpy()    */   printf("Return value of function: %s\n", strcpy(str, "Apple"));   printf("String str1: %s\n", str);   return 0;}

输出:

Return value of function: AppleString str1: Apple

相关文章:

    C – strcat()示例C – strchr()示例C – strcmp()示例C – strcoll()示例

相关推荐