Computer >> 컴퓨터 >  >> 프로그래밍 >> C 프로그래밍

C 언어 strncpy() 함수 완벽 정리 – 문자열 복사와 부분 문자열 추출 방법

C 표준 라이브러리 함수 char *strncpy(char *dest, const char *src, size_t n)src가 가리키는 문자열에서 최대 n개의 문자를 dest로 복사합니다. 만약 src의 길이가 n보다 짧다면, dest의 나머지 공간은 널(null) 바이트로 채워집니다.

참고로, 문자(character)들이 모인 배열을 문자열(string)이라고 부릅니다.

문자열 선언

문자열 배열의 선언 형식은 다음과 같습니다.

char stringname[size];

예를 들어 char string[50];은 최대 50자를 저장할 수 있는 문자열을 의미합니다.

문자열 초기화

  • 문자 상수를 이용한 초기화:
char string[10] = { 'H', 'e', 'l', 'l', 'o', '\0' };
  • 문자열 상수를 이용한 초기화:
char string[10] = "Hello";

접근(Accessing): 제어 문자열 "%s"를 사용하면 문자열에서 널 문자('\0')를 만날 때까지 문자열 전체를 읽거나 출력할 수 있습니다.

strncpy() 함수란?

  • 소스(source) 문자열에서 'n'개의 문자를 대상(destination) 문자열로 복사하는 데 사용됩니다.
  • 대상 문자열의 크기는 소스 문자열보다 크거나 같아야 합니다.

함수의 기본 문법은 다음과 같습니다.

strncpy(대상 문자열, 소스 문자열, n);

예제 프로그램 1: 기본적인 문자열 복사

다음은 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

이처럼 strncpy() 함수는 문자열의 일부만 복사할 수 있으며, 부분 문자열(substring)을 추출하는 용도로도 활용됩니다.

예제 프로그램 2: 부분 문자열 추출

다음 예제는 strncpy() 함수를 활용해 문자열 중간에서 원하는 부분만 잘라내는 방법을 보여줍니다.

char result[10], s1[15] = "Jan 10 2010";
strncpy(result, &s1[4], 2);
result[2] = '\0';

실행 결과

Result = 10

위 코드에서 &s1[4]는 문자열 "Jan 10 2010"의 다섯 번째 문자부터 시작하는 위치를 가리킵니다. 여기서 2글자("10")를 복사한 뒤 마지막에 널 문자를 붙여 하나의 완전한 문자열로 만드는 원리입니다.

예제 프로그램 3: strncpy() 종합 활용 예제

다음은 strncpy 라이브러리 함수를 사용해 소스 문자열에서 n개의 문자를 대상 문자열로 복사하고, 그 결과들을 연결(concatenate)하는 C 프로그램입니다.

#include<stdio.h>
#include<string.h>
void main(){
    //소스 문자열과 대상 문자열 선언//
    char source[45],destination[50];
    char destination1[10],destination2[10],destination3[10],destination4[10];
    //사용자로부터 소스 문자열 입력 받기//
    printf("Enter the source string :");
    gets(source);
    //strncpy를 이용해 새로운 대상 문자열 추출//
    strncpy(destination1,source,2);
    printf("The first destination value is : ");
    destination1[2]='\0';//출력 전 반드시 널 값을 지정해야 쓰레기 값이 출력되지 않습니다//
    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);
    //위의 결과들을 모두 연결//
    strcat(destination1,destination2);
    strcat(destination1,destination3);
    printf("The modified destination string :");
    printf("%s3",destination1);
}

실행 결과

위 프로그램을 실행하면 다음과 같은 결과가 출력됩니다.

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

strncpy() 사용 시 주의 사항

  • 복사 후 대상 문자열이 자동으로 널 종료되지 않을 수 있으므로, 출력하기 전에 반드시 '\0'을 직접 지정해야 쓰레기 값(garbage value)이 출력되는 것을 막을 수 있습니다.
  • 버퍼 오버플로우를 방지하려면 대상 버퍼의 크기가 복사할 문자 수보다 충분히 커야 합니다.
  • 표준에서 권장하지 않는 gets() 대신 fgets()를 사용하면 더 안전하게 문자열을 입력받을 수 있습니다.