C 语言实例 - 字符串复制

将一个变量的字符串复制到另外一个变量中。

实例 - 使用 strcpy()

c 复制代码
#include <stdio.h>
#include <string.h>
 
int main()
{
   char src[40];
   char dest[100];
  
   memset(dest, '\0', sizeof(dest));
   strcpy(src, "This is runoob.com");
   strcpy(dest, src);
 
   printf("最终的目标字符串: %s\n", dest);
   
   return(0);
}

输出结果为:

c 复制代码
最终的目标字符串: This is runoob.com

实例 - 不使用 strcpy()

c 复制代码
#include <stdio.h>
 
int main()
{
    char s1[100], s2[100], i;
 
    printf("字符串 s1: ");
    scanf("%s",s1);
 
    for(i = 0; s1[i] != '\0'; ++i)
    {
        s2[i] = s1[i];
    }
 
    s2[i] = '\0';
    printf("字符串 s2: %s", s2);
 
    return 0;
}

输出结果为:

c 复制代码
字符串 s1: runoob
字符串 s2: runoob
相关推荐
geovindu1 小时前
python: Decision Tree
开发语言·后端·python·决策树
时间的情敌2 小时前
Three.js 工业场景性能优化合集|大批量管线、InstancedMesh 实例化、合并 Geometry、显存释放
开发语言·javascript·性能优化·three.js
Go-higher2 小时前
C语言--数据结构-栈、队列、堆
c语言·数据结构
步峰代理-盾山2 小时前
R语言爬虫实战:使用httr与XML解析网页数据并进行统计分析
xml·开发语言·爬虫·r语言·网络爬虫
sharemylove12 小时前
Java集合框架全面详解
java·开发语言·经验分享·笔记·学习
郝学胜-神的一滴17 小时前
Effective Python 条款43:自定义容器类
开发语言·windows·python·pandas·scikit-learn·pyqt
2601_9664923117 小时前
C语言变量揭秘
c语言·变量·编译器·线程安全·内存布局
好焊孙辉18 小时前
一条产线省下 30 个电机位:Z 轴和 R 轴,该合成一个了
开发语言·r语言
布莱克60518 小时前
Swift 中的逃逸闭包与非逃逸闭包:@escaping 到底在做什么
开发语言·ios·swift·闭包·逃逸
郝学胜-神的一滴18 小时前
Effective STL 条款 14:用扩容函数避免重新分配
linux·开发语言·网络·数据结构·c++·单片机