C语言字符串函数

C语言 strcpy()函数用于将字符串复制到数组。它是C语言的字符串函数之一。

该函数不需要指定复制的长度,遇到'\0'结束复制,看下面的例子2。

语法

语法如下:
char *strcpy(char *destin, char *source)

    参数

    • destin:目标数组。
    • source:原字符串。

    功能

    将原source字符串复制到destin目标字符串。destin必须有足够的空间来容纳source字符串。

    返回值

    返回目标字符串destin,destin结尾处字符(NULL)的指针。

    程序示例

    介绍一个例子,了解C语言 strcpy()函数的使用方法。

    例1

    全部复制

    #include <stdio.h>
    #include <string.h>
    
    int main(){
        char dest[16];//目标
        char *src = "www.yxjc123.com" ;//原字符串
        strcpy(dest, src);
        printf("%s\n",dest);  int len = strlen(dest);
        printf("长度:%d\n",len);
    
        return 0;
    } 
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    程序运行结果:

    www.yxjc123.com
    长度:15

    因为字符串末尾有一个'\0',所以要预留一个空间长度为16。

    例2

    碰到'\0'结束的例子

    #include <stdio.h>
    #include <string.h>
    
    int main(){
        char dest[16];//目标
        char *src = "www.yxjc123.\0com" ;//原字符串
        int len;
        strcpy(dest, src);
        printf("%s\n",dest);  
        len = strlen(dest);
        printf("长度:%d\n",len);
    
        getchar();
        return 0;
    } 
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    输出:

    www.yxjc123.
    长度:12