[Deep Dive] C언어의 str함수

C 언어에서 문자열(string)을 다룰 때 사용하는 표준 라이브러리 함수들은 string.h 헤더 파일에 정의되어 있으며, 이 함수들은 문자 배열(char 배열)을 다룰 때 자주 사용된다. 아래는 주요 str 관련 함수들과 그 설명이다.


1. strlen – 문자열 길이 구하기

size_t strlen(const char *s);

설명: 문자열의 길이를 구한다. 널 문자('\0')는 포함하지 않는다.

예제:

#include <stdio.h>
#include <string.h>

int main() {
    char str[] = "hello";
    printf("Length: %zu\n", strlen(str)); // 출력: Length: 5
}

2. strcpy – 문자열 복사

char *strcpy(char *dest, const char *src);
  • 설명: src의 문자열을 dest에 복사한다. 널 문자까지 포함해서 복사함.
  • 주의: dest에 충분한 크기가 있어야 함.

예제:

#include <stdio.h>
#include <string.h>

int main() {
    char src[] = "world";
    char dest[10];
    strcpy(dest, src);
    printf("Copied: %s\n", dest); // 출력: Copied: world
}

3. strncpy – 문자열 일부 복사

char *strncpy(char *dest, const char *src, size_t n);
  • 설명: src에서 최대 n개의 문자만 복사. 널 문자가 없으면 직접 넣어줘야 함.
  • 주의: 널 문자가 보장되지 않음. dest[n] = '\0';로 마무리하는 게 좋다.

예시:

#include <stdio.h>
#include <string.h>

int main() {
    char src[] = "banana";
    char dest[10];
    strncpy(dest, src, 3);
    dest[3] = '\0'; // 꼭 null-termination!
    printf("Partial Copy: %s\n", dest); // 출력: Partial Copy: ban
}

4. strcat – 문자열 이어붙이기

char *strcat(char *dest, const char *src);
  • 설명: src를 dest 뒤에 붙임. dest는 널 문자로 끝나는 문자열이어야 함.
  • 주의: dest의 크기를 충분히 확보해야 함.

예시:

#include <stdio.h>
#include <string.h>

int main() {
    char dest[20] = "hello ";
    char src[] = "world";
    strcat(dest, src);
    printf("Concatenated: %s\n", dest); // 출력: Concatenated: hello world
}

5. strncat – 문자열 일부만 이어 붙이기

char *strncat(char *dest, const char *src, size_t n);

설명: src의 최대 n 문자만 dest 뒤에 붙인다.

예시:

#include <stdio.h>
#include <string.h>

int main() {
    char dest[20] = "data";
    char src[] = "base";
    strncat(dest, src, 2); // "ba"만 붙음
    printf("Partial Concat: %s\n", dest); // 출력: databa
}

6. strcmp – 문자열 비교

int strcmp(const char *s1, const char *s2);

설명: s1과 s2를 사전순으로 비교함.

반환값 의미
0 s1과 s2가 같다
< 0 s1이 s2보다 사전순으로 앞이다
> 0 s1이 s2보다 사전순으로 뒤이다

예시:

strcmp("abc", "abd")  // 'c' - 'd' = -1 → 결과: -1
strcmp("hello", "hell")  // 'o' vs '\0' → 'o'(111) - '\0'(0) = 111 → 결과: 양수
#include <stdio.h>
#include <string.h>

int main() {
    printf("%d\n", strcmp("apple", "banana")); // 출력: 음수
    printf("%d\n", strcmp("zebra", "ant"));    // 출력: 양수
    printf("%d\n", strcmp("cat", "cat"));      // 출력: 0
}

7. strncmp – 문자열 앞부분만 비교

int strncmp(const char *s1, const char *s2, size_t n);
  • 설명: 앞의 n 글자만 비교함.

예시:

#include <stdio.h>
#include <string.h>

int main() {
    printf("%d\n", strncmp("abcdef", "abcxyz", 3)); // 출력: 0
    printf("%d\n", strncmp("hello", "help", 4));    // 출력: 음수
}

8. strchr – 문자 찾기 (처음 등장)

char *strchr(const char *s, int c);
  • 설명: 문자열 s에서 문자 c가 처음 나오는 위치를 반환.

예시:

#include <stdio.h>
#include <string.h>

int main() {
    char *result = strchr("abcdef", 'd');
    if (result) printf("Found: %s\n", result); // 출력: def
}

9. strrchr – 문자 찾기 (마지막 등장)

char *strrchr(const char *s, int c);
  • 설명: 문자 c가 마지막으로 등장하는 위치 반환.

예시:

#include <stdio.h>
#include <string.h>

int main() {
    char *result = strrchr("banana", 'a');
    if (result) printf("Last 'a': %s\n", result); // 출력: a
}

10. strstr – 부분 문자열 찾기

char *strstr(const char *haystack, const char *needle);
  • 설명: 문자열 haystack에서 needle이 처음 나타나는 위치를 반환.

예시:

#include <stdio.h>
#include <string.h>

int main() {
    char *result = strstr("I love programming", "love");
    if (result) printf("Found: %s\n", result); // 출력: love programming
}

11. strtok – 문자열 분할 (토큰화)

char *strtok(char *str, const char *delim);
  • 설명: delim에 있는 구분자를 기준으로 문자열을 나누어 토큰을 반환한다.
  • 주의: 내부적으로 상태를 기억하므로 멀티스레드 환경에서는 사용 금지. 대신 strtok_r 사용.

예시:

#include <stdio.h>
#include <string.h>

int main() {
    char str[] = "a,b,c";
    char *token = strtok(str, ",");
    while (token != NULL) {
        printf("Token: %s\n", token);
        token = strtok(NULL, ",");
    }
}

12. strdup – 문자열 복사 (동적 할당)

char *strdup(const char *s);
  • 설명: 문자열을 malloc으로 복사해 새로운 메모리를 반환 (해제 필요). POSIX 함수이며 일부 환경에서는 별도 선언 필요.

예시:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main() {
    char *original = "hello";
    char *copy = strdup(original);
    printf("Copy: %s\n", copy); // 출력: hello
    free(copy);
}