열렬히.뛰기

문자와 문자열

Language > 프로그래밍 언어 > C > 문자와 문자열

문자열 출력하기

c
#include <stdio.h>

int main() {
        int i;

        char str[4] = "abcd"; // 배열의 크기 = 문자 수
        char str2[] = "서울은 아름다운 곳";

        printf("%s\n", str);
        printf("%s\n", str2);

}

문자열 입력하기

한 줄의 라인을 문자열로 입력받으려면 새로운 함수를 써야 한다.을 써야 한다.

scanf()는 하나의 단어밖에 입력받지 못한다.
c
// 문자열 입력하기 1
#include <stdio.h>
int main() {
        char name[100];
        char address[100];

        printf("이름을 입력하시오: ");
        scanf("%s", name);
        printf("현재 거주하고 있는 주소를 입력하시요");
        scanf("%s", address); // 배열의 이름이 배열의 주소.
                              // &를 붙이지 않음.

        printf(name);
        printf(address);
}
c
// 문자열 입출력
#include <stdio.h>
int main() {
        char name[100];
        char address[100];

        printf("이름을 입력하시오: ");
        fgets(name, 100, stdin);
        printf("현재 거주하고 있는 주소를 입력하시요");
        fgets(address, 100, stdin); // 배열의 이름이 배열의 주소.
                              // &를 붙이지 않음.

        fputs(name, stdout);
        fputs(address, stdout);
}
  • gets() , puts() 는 더 이상 버퍼 오버플로우의 문제로 사용하지 않음.

  • fgets([변수명], [배열의 길이], stdin)

    fgets([변수명], sizeof([변수명]), stdin)

  • fputs([변수명], stdout)

문자 처리 라이브러리

반드시 헤더파일 <ctype.h>를 포함해야 한다.

c
# include <ctype.h>

// 검사 라이브러리 : is + [이름] 구조로 되어있다.
isupper(a);
iscntrl(c);
isxdigit(c);

// 변환 라이브러리
toupper(c);
tolower(c);

입력된 문자를 대문자로 출력하는 프로그램을 만들어보자.

c
#include <stdio.h>
#include <ctype.h>

int main() {
        int c;
        while((c = getchar()) != EOF) {
                if (islower(c)) {
                        c = toupper(c);
                }
                putchar(c);
        }
}
// 강제 종료하려면 ctrl + c 키를 누르면 된다.

문자열 처리 라이브러리

반드시 헤더파일 <string.h>를 포함해야 한다.

c
#include <string.h>

// 문자열 처리 라이브러리
strlen(s) // 문자열 s의 길이를 구한다.

strcpy(s1, s2, n)  // s2를 s1에 복사한다.
strcat(s1, s2, n)  // s2를 s1 뒤에 붙인다.
strcmp(s1, s2, n)  /* s1와 s2를 비교한다. 둘이 같으면 0, 
사전 상 앞에 있으면 음수를, 사전 상 뒤에 잇으면 양수를 반환. */


strncpy(s1, s2, n)  // s2의 최대 n개 문자를 s1에 복사한다.
strncat(s1, s2, n)  // s2의 최대 n개 문자를 s1 뒤에 붙인다. 
strncmp(s1, s2, n)  // 최대 n개 문자까지 s1와 s2를 비교한다.

strchr(s, c);       // 문자열 s안에 문자 c 찾기
strstr(s1, s2);     // 문자열 s1 안에 s2 찾기
strtok(s, [구분자]) // [구분자]로 문자열 자르기 
c
#include <stdio.h>
#include <string.h>
void connect() {
        char string[80];
        strcpy(string, "Hello World from ");
        strcat(string, "Korea");
        fputs(string, stdout);
}


int main() {
        char str1[100];
        char str2[100];
        fgets(str1, sizeof(str1), stdin);
        fgets(str2, sizeof(str2), stdin);

        // 문자열 길이 확인하기
        printf("str1의 길이 : %d\n", strlen(str1));

        // 문자열 복사하기
        char str_copy[100];
        strcpy(str1, str_copy);
        printf("\n 문자열 복사하기\n");
        fputs(str_copy, stdout);

        // 문자열 연결하기
        printf("\n 문자열 연결하기\n");
        connect();

        // 문자열 비교하기
        printf("\n 문자열 연결하기\n");
        printf("%d\n", strcmp(str1, str2));

        // 문자열 토큰 분리
        printf("\n 토큰 검색\n");
				printf("\n 토큰 검색\n");
        printf("문자열 입력 : ");
        char str3[100];
        char seps[] = " ";
        fgets(str3, sizeof(str3), stdin);

        token = strtok(s, seps);
        while(token != NULL) {
                printf("토큰 : %s\n", token);
                token = strtok(NULL, seps);
        }

        // 문자열 수치 변환
        printf("\n 문자열 수치 변환\n");

        char s[] = 100;
        int value;

        sscanf(s, "%d", &value);
        printf("%d \n", value);
        value++;

        sprintf(s, "%d", value);
        printf("%s \n", value);

}

2차원 문자열

c
#include <stdio.h>

int main() {
        char fruits[3][20];

        for(int i = 0; i < 3; i++) {
                printf("과일 이름 : ", fruits[i]);
                scanf("%s", fruits[i]);
        }

        for(int i = 0; i < 3; i++) {
                printf("%d번째 과일 : %s\n", i, fruits[i]);
        }

}