使用 strcpy() 函数复制字符串的 C 程序
在本部分中,我们将学习如何在不使用 strcpy() 函数的情况下,将一个字符串复制到另一个字符串。为了解决这个问题,我们可以编写一个可以类似于 strcpy() 的函数,但这里我们将使用其他一些技巧。我们将使用另一个库函数来将一个字符串复制到另一个字符串。
逻辑非常简单。这里我们将使用 sprintf() 函数。此函数用于将某些值或行打印到字符串中,但不是控制台。这是 printf() 和 sprintf() 唯一不同的地方。以下第一个参数是字符串缓冲区。在其中我们希望保存我们的数据。
Input − Take one string "Hello World" Output − It will copy that string into another string. "Hello World"
算法
Step 1: Take a string Step 2: Create an empty string buffer to store result Step 3: Use sprintf() to copy the string Step 4: End
示例代码
#include<stdio.h>
main() {
char str[50]; //create an empty string to store another string
char *myString = "Program to copy a String";
sprintf(str, "%s", myString);//Use sprintf to copy string from myString to str
printf("The String is: %s", str);
}输出
The String is: Program to copy a String
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP