Contents

Develop
2015.11.10 15:49

[c] 한글 문자열 출력

조회 수 1780 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄

영어는 1byte, 한글은 2byte 차지한다.

따라서 문자열 처리할 때 한 포인터씩 출력을 하게 되면 한글이 깨지는 현상이 발생한다.

예를 들어 한글과 영어가 섞여있는 문자열을 출력할 때 다음과 같은 소스를 이용하면 한글이 깨져서 출력된다.

 

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

const int MAX_SIZE = 1000;


int main(){
    FILE *fp = fopen("test.txt","r");
    char* inp = (char*)malloc(sizeof(char)*MAX_SIZE);
    int i;

    while(fgets(inp, MAX_SIZE, fp)){

        printf("%s" , inp);

        for(i = 0 ; i < strlen(inp) ; i++){
            printf("%c  " , inp[i]) ;
        }
        printf("\n");
    }
    
    return 0;
}

 

 

그렇다면, 한글과 영어를 판단해서 영어는 1byte, 한글은 2byte를 출력해야 할텐데,

어떻게 하면 한글인지 영어인지 확인할 수 있을까?

 

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

const int MAX_SIZE = 1000;

typedef enum {false, true} bool;

int main(){
    FILE *fp = fopen("test.txt","r");
    char* inp = (char*)malloc(sizeof(char)*MAX_SIZE);
    int i;
    bool HANGUL = false;


    while(fgets(inp, MAX_SIZE, fp)){

        printf("%s" , inp);

        for(i = 0 ; i < strlen(inp) ; i++){
            if((inp[i] & 0x80) == 0x80) HANGUL = true; //한글인지 확인
            if(!HANGUL)printf("%c  " , inp[i]) ; //아니면 그냥 출력
            else{
                printf("%c%c" , inp[i] , inp[i+1]); //한글이면 2byte 출력
                i++;
            }
            HANGUL = false;
        }
        printf("\n");
    }
    
    return 0;
}

 

위의 소스는 각 char 마다 한글인지 아닌지를 판단해서 한글인 경우 2byte를 출력하게 해준다.

 


?

List of Articles
번호 분류 제목 글쓴이 날짜 조회 수
177 System/OS SSH Passwordless Login Using SSH Keygen in 5 Easy Steps file hooni 2019.11.22 1523
176 System/OS How to Install and Use wget on Mac file hooni 2020.09.03 1514
175 Etc 아이폰의 터치스크린 정확도 file hooni 2015.04.01 1501
174 Develop [ios] Swift 4 String, Date, DateFormatter 예제 hooni 2018.10.18 1497
173 System/OS RPA란? 어디에 어떻게 쓰이고 누가 만드나? file hooni 2020.01.28 1492
172 System/OS Configure Postfix to Use Gmail SMTP on Ubuntu 18.04 file hooni 2020.02.07 1480
171 Develop [ios] How to set up clang formatter hooni 2015.09.17 1461
170 Etc 모바일 프로그래머가 갖추어야 할 필수 역량 file hooni 2017.02.16 1451
169 Develop [android] 간단한 SQLIite 예제 hooni 2017.06.14 1443
168 System/OS [mac] Mac OS 패키지 매니저, HomeBrew file hooni 2015.01.03 1440
167 Etc ISMS 인증기준 – 정보보호대책 (시스템개발보안) file hooni 2016.12.01 1439
166 Develop [php] 한글 문자열 자르기 (utf-8) hooni 2015.11.10 1438
Board Pagination Prev 1 ... 79 80 81 82 83 84 85 86 87 88 ... 98 Next
/ 98