영어로 읽는 코딩

# 17 [C] 아스키 코드의 활용

```/*count digits, white space, others*/
int atoi(char[]);

int main(void)
{
char ndigit[] = "589";

printf("%d \n", atoi(ndigit));

return 0;
}

int atoi(char s[]) {

int i = 0, n = 0;

for (i = 0; s[i] >= '0' && s[i] <= '9'; i++)
n = 10 * n + (s[i] - '0');
return  n;
}

/*The C Programming Language (second edition, Prentice Hall)
by Brian W. Kernighan and Dennis M. RitchieS*/```

A char is just a small integer, so chars may be freely used in arithmetic expressions. This permits considerable flexibility in certain kinds of character transformations. One is exemplified by this naive implementation of the function atoi which converts a string of digits into its numeric equivalent.

As we discussed in Chapter 1, the expression

s[i] – ‘0’

gives the numeric value of the character stored in s [ i ] , because the values of

0 ’ , ’ 1 ’ , etc., form a contiguous increasing sequence.

```#include <stdio.h>

int lower(int);

int main(void)
{
char alpha = 'F';

printf("%c \n", lower(alpha));

return 0;
}

int lower(int c) {

if (c >= 'A' && c <= 'Z')
return c + 'a' - 'A';
else
return c;
}```

Another example of char to int conversion is the function lower, which maps a single character to lower case for the ASCII character set. If the character is not an upper case letter, lower returns it unchanged.

This works for ASCII because corresponding upper case and lower case letters are a fixed distance apart as numeric values and each alphabet is contiguous - there is nothing but letters between A and z. This latter observation is not true of the EBCDIC character set, however, so this code would convert more than just letters in EBCDIC.

[The C Programming Language (second edition, Prentice Hall) by Brian W. Kernighan and Dennis M. Ritchie] p. 42-43

### 댓글

댓글 본문
버전 관리
 2018-07-31 10:10:35 Yoo Moon Il
현재 버전 2018-07-31 10:10:35 graphittie 자세히 보기
• 토픽 0
• 모듈 0
• 코스 0
• 봤어요 0
• 댓글 0
• 명예의 전당 0