1.6 配列, 演習1-13, 演習1-14 K&R プログラミング言語C
2009年12月01日
1.6 配列
if (c >= '0' && c <= '9') {
ASCIIコードでは、'0'
は 48
、'9'
は 57
、となるので上記のコードは以下と同じ意味となる。
if (c >= 48 && c <= 57) {
c
が数字の場合以下のコードの配列の添字は 0
から 9
の範囲の数となる。
ndigit[c-'0'];
演習1-13
#include <stdio.h> #define IN 1 #define OUT 0 #define MAX_WORD_LENGTH 20 int main(int argc, char *argv[]) { int c, i, j, len, state; int lword[MAX_WORD_LENGTH]; state = OUT; len = 0; for (i = 0; i < MAX_WORD_LENGTH; ++i) { lword[i] = 0; } while ((c = getchar()) != EOF) { if (c == ' ' || c == '\n' || c == '\t' || c == ',' || c == '.') { if (len > 0) { ++lword[len]; } state = OUT; len = 0; } else if (state == OUT) { state = IN; ++len; } else if (state == IN) { ++len; } } printf("length : count\n"); for (i = 0; i < MAX_WORD_LENGTH; ++i) { printf("%6d : ", i+1); for (j = 0; j < lword[i+1]; ++j) { printf("*"); } printf("\n"); } return 0; }
実行結果
$ cat bible.txt Balak puts Balaam to work almost immediately upon arriving. The diviner has Balak build seven altars, on each of which he offers a bull and a ram. The bull and ram are the prime animals to offer because of their value, and the number seven has a long history of being especially propitious. By these offerings, Balaam is trying to ensure his ability to bribe a curse out of God. $ cat bible.txt | ./ex1-13 length : count 1 : **** 2 : ************ 3 : *************** 4 : ******* 5 : ************** 6 : ******** 7 : ***** 8 : * 9 : * 10 : ** 11 : * 12 : 13 : 14 : 15 : 16 : 17 : 18 : 19 : 20 : $
演習1-14
アルファベット(a-z)のみをカウントし、大文字・小文字の区別はしないようにした。
#include <stdio.h> #define NALPHABET 24 int main(int argc, char *argv[]) { int c, i, j; int alphabets[NALPHABET]; for (i = 0; i < NALPHABET; ++i) { alphabets[i] = 0; } while ((c = getchar()) != EOF) { if (c >= 'A' && c <= 'Z') { c = c + ('a' - 'A'); ++alphabets[c - 'a']; } else if (c >= 'a' && c <= 'z') { ++alphabets[c - 'a']; } } for (i = 0; i < NALPHABET; ++i) { printf("%c : ", i+'a'); for (j = 0; j < alphabets[i]; ++j) { printf("*"); } printf("\n"); } return 0; }
$ cat bible.txt Balak puts Balaam to work almost immediately upon arriving. The diviner has Balak build seven altars, on each of which he offers a bull and a ram. The bull and ram are the prime animals to offer because of their value, and the number seven has a long history of being especially propitious. By these offerings, Balaam is trying to ensure his ability to bribe a curse out of God. $ cat bible.txt | ./ex1-14 a : ********************************** b : ************** c : ***** d : ******* e : ******************************** f : ********** g : ****** h : ************** i : *********************** j : k : *** l : ****************** m : ********** n : **************** o : ********************* p : ****** q : r : ******************** s : ******************* t : ******************* u : ************ v : ***** w : ** x : $
プログラミング言語C 第2版 ANSI規格準拠
posted with amazlet at 09.11.27
B.W. カーニハン D.M. リッチー
共立出版
売り上げランキング: 9726
共立出版
売り上げランキング: 9726