Computer >> 컴퓨터 >  >> 프로그램 작성 >> C 프로그래밍

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