/*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