C 라이브러리 함수 char *strncpy(char *dest, const char *src, size_t n) src가 가리키는 문자열에서 최대 n개의 문자를 복사합니다. 목적지로 . src의 길이가 n보다 작은 경우 dest의 나머지 부분은 null 바이트로 채워집니다.
문자 배열을 문자열이라고 합니다.
선언
다음은 배열에 대한 선언입니다 -
char stringname [size];
예를 들어 - char string[50]; 길이 50자의 문자열
초기화
- 단일 문자 상수 사용 -
char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’} - 문자열 상수 사용하기 -
char string[10] = "Hello":;
액세스 − '\0'이 나타날 때까지 문자열에 액세스하는 데 사용되는 제어 문자열 "%s"가 있습니다.
strncpy() 함수
-
이 함수는 원본 문자열의 'n'자를 대상 문자열로 복사하는 데 사용됩니다.
-
대상 문자열의 길이가 원본 문자열보다 크거나 같습니다.
구문은 다음과 같습니다 -
strncpy (Destination string, Source String, n);
예시 프로그램
다음은 strncpy() 함수를 위한 C 프로그램입니다 -
#include<string.h>
main ( ){
char a[50], b[50];
printf ("enter a string");
gets (a);
strncpy (b,a,3);
b[3] = '\0';
printf ("copied string = %s",b);
getch ( );
} 출력
위의 프로그램을 실행하면 다음과 같은 결과가 나온다 -
Enter a string : Hello Copied string = Hel

부분 문자열 추출에도 사용됩니다.
예시 1
다음 예제는 strncpy() 함수의 사용법을 보여줍니다.
char result[10], s1[15] = "Jan 10 2010"; strncpy (result, &s1[4], 2); result[2] = ‘\0’
출력
위의 프로그램을 실행하면 다음과 같은 결과가 나온다 -
Result = 10

예시 2
strncpy에 대한 다른 예를 살펴보겠습니다.
다음은 strncpy 라이브러리 함수 -
를 사용하여 소스 문자열에서 대상 문자열로 n개의 문자를 복사하는 C 프로그램입니다.#include<stdio.h>
#include<string.h>
void main(){
//Declaring source and destination strings//
char source[45],destination[50];
char destination1[10],destination2[10],destination3[10],destination4[10];
//Reading source string and destination string from user//
printf("Enter the source string :");
gets(source);
//Extracting the new destination string using strncpy//
strncpy(destination1,source,2);
printf("The first destination value is : ");
destination1[2]='\0';//Garbage value is being printed in the o/p because always assign null value before printing O/p//
puts(destination1);
strncpy(destination2,&source[8],1);
printf("The second destination value is : ");
destination2[1]='\0';
puts(destination2);
strncpy(destination3,&source[12],1);
printf("The third destination value is : ");
destination3[1]='\0';
puts(destination3);
//Concatenate all the above results//
strcat(destination1,destination2);
strcat(destination1,destination3);
printf("The modified destination string :");
printf("%s3",destination1);//Is there a logical way to concatenate numbers to the destination string?//
} 출력
위의 프로그램을 실행하면 다음과 같은 결과가 나온다 -
Enter the source string :Tutorials Point The first destination value is : Tu The second destination value is : s The third destination value is : i The modified destination string :Tusi3