2014년 12월 18일 목요일

[Basic Skill] 문자를 Integer로 변환하기 (Ascii to Integer)

문자열을 int형으로 변환하기 위해서는 0~10 이라는 숫자를 표시하는 문자에
'0' 이라는 숫자를 나타내는 Ascii 값인 48을 빼주면 된다.

간단히 말해
0 이라는 문자는 Ascii 값 48 이고, 1이라는 문자는 Ascii값 49... 로 되어 있기 때문에

예로 2라는 숫자는 50 이라는 Ascii 코드로 약속 되어 있기 때문에

50 - 48 을 통해 2 라는 숫자가 나오고, 그 2라를 값을 int형으로 지정하면 된다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 문자형 숫자를 Integer로 변환하기 (1~10, A~F)
int asciiToInteger(const char * str){
    int result = 0;
 
    while (*str){
        if (*str >= '0' && *str <= '9'){ // 0~9 의 문자일 경우
            result = result * 10 + *str - '0';
        }
        else if (*str >= 'A' && *str <= 'F'){ // A~F의 문자일 경우
            result = result * 10 + (*str - 'A'+ 10;
        }        
        str++;
    }
 
    return result;
}
 
cs

[Basic Skill] 문자열 복사 (strcpy) 구현하기

문자를 복사하기 위해서는 해당 문자열의 시작과 끝 위치를 정해서 아래와 같이
문자열 복사가 가능함.



1
2
3
4
5
6
7
8
void stringCopy(char *dest, const char *src, int start, int end){
    int i = 0;
    for (int i = 0; i < end - start; i++){
        *(dest + i) = *(src + start + i);
    }
    // printf("stringCopy dest %s src %s \n", dest, src);
    return;
}
cs

[Basic Skill] 문자열의 길이 구현하기 strLength

문자열의 길이를 구하기 위해서 문자 배열의 길이를 구하면 됨.
문자 배열에서 '\0' 혹은 'NULL' 을 만나기 전 까지 count 하면 그게 문제 길이가 됩니다.


1
2
3
4
5
6
7
8
int strLength(const char *str){
    int strlen = 0;
        while (*(str++) != '\0'){
            strlen++;
        };
        // printf("string length = %d \n", strlen);
    return strlen;
}
cs