C 표준 라이브러리 함수 char *strncat(char *dest, const char *src, size_t n)는 src가 가리키는 문자열을 dest가 가리키는 문자열의 끝에 최대 n개 문자까지만 이어 붙이는(연결하는) 함수입니다.
C 언어에서 문자(character)들의 배열을 문자열(string)이라고 부릅니다.
문자열 선언
배열은 다음과 같이 선언합니다.
char stringname[size];
예를 들어 char string[50];은 길이 50자를 저장할 수 있는 문자열입니다.
문자열 초기화
- 단일 문자 상수를 이용한 초기화
char string[10] = { 'H', 'e', 'l', 'l', 'o', '\0' };
- 문자열 상수를 이용한 초기화
char string[10] = "Hello";
접근 – 제어 문자열 %s를 사용하면 널 문자('\0')를 만날 때까지 문자열 전체를 읽거나 출력할 수 있습니다.
strncat() 함수의 특징
- 한 문자열에서 n개의 문자를 잘라 다른 문자열에 결합(연결)할 때 사용합니다.
- 대상 문자열(dest)은 연결된 결과를 모두 담을 수 있도록 소스 문자열보다 충분히 크게 선언해야 합니다.
- 연결된 최종 결과 문자열은 대상 문자열(dest)에 저장됩니다.
함수 구문은 다음과 같습니다.
strncat(대상 문자열, 소스 문자열, n);
예제 1: strncat() 기본 사용법
다음 프로그램은 strncat() 함수의 기본적인 사용법을 보여줍니다.
#include <stdio.h>
#include <string.h>
int main(void){
char a[30] = "Hello ";
char b[20] = "Good Morning";
/* b에서 앞 4글자("Good")만 a에 이어 붙임 */
strncat(a, b, 4);
printf("concatenated string = %s\n", a);
return 0;
}
실행 결과
위 프로그램을 실행하면 다음과 같은 결과가 출력됩니다.
Concatenated string = Hello Good.
예제 2: 사용자 입력 문자열에서 n개 문자 연결하기
다음은 strncat() 라이브러리 함수를 사용해 소스 문자열에서 n개의 문자를 대상 문자열로 연결하는 C 프로그램입니다.
#include <stdio.h>
#include <string.h>
void main(){
// 소스 문자열과 대상 문자열 선언 //
char source[45], destination[50];
// 사용자로부터 두 문자열 입력 받기 //
printf("Enter the source string : ");
gets(source);
printf("Enter the destination string before : ");
gets(destination);
// 연결 작업 수행 //
destination[2] = '\0';
strncat(destination, source, 2);
strncat(destination, &source[4], 1);
// 수정된 대상 문자열 출력 //
printf("The modified destination string : ");
puts(destination);
}
실행 결과
위 프로그램을 실행하면 다음과 같은 결과가 출력됩니다.
Enter the source string : Tutorials Point Enter the destination string before : Tutorials Point C Programming The modified destination string : TuTur
동작 원리 단계별 살펴보기
예제 2의 실행 과정을 단계별로 정리하면 다음과 같습니다.
destination[2] = '\0';– 대상 문자열을 세 번째 문자에서 잘라 "Tu"로 만듭니다.strncat(destination, source, 2);– 소스 문자열의 앞 2글자 "Tu"를 이어 붙여 "TuTu"가 됩니다.strncat(destination, &source[4], 1);– 소스 문자열의 5번째 문자 'r'부터 1글자를 이어 붙여 최종 결과 "TuTur"가 완성됩니다.
참고: 예제에 사용된 gets() 함수는 입력 길이를 제한할 수 없어 버퍼 오버플로 위험이 있으며 C11 표준에서 제거되었습니다. 실제 프로젝트에서는 fgets() 사용을 권장합니다.