文字列を指定された回数だけ連続して表示するプログラム
#include <stdio.h> /*--- 文字列strをno回表示する ---*/ void put_stringn(const char str[], int no) { while (no-- > 0) printf("%s", str); } int main(void) { char str[100]; int no; printf("文字列を入力してください:"); scanf("%s", str); printf("何回表示しますか:"); scanf("%d", &no); put_stringn(str, no); putchar('\n'); return (0); }
実行結果
文字列を入力してください:String 何回表示しますか:3 StringStringString
文字列をそのまま表示するプログラム(2)
#include <stdio.h> /*--- 文字列を表示 ---*/ void put_string(const char str[]) { printf("%s", str); } int main(void) { char str[100]; printf("文字列を入力してください:"); scanf("%s", str); put_string(str); putchar('\n'); return (0); }
実行結果
文字列を入力してください:SEC SEC
文字列を一文字ずつなぞりながら表示するプログラム
#include <stdio.h> /*--- 文字列を表示 ---*/ void put_string(const char str[]) { unsigned i = 0; while (str[i]) putchar(str[i++]); } int main(void) { char str[100]; printf("文字列を入力してください:"); scanf("%s", str); put_string(str); putchar('\n'); return (0); }
実行結果
文字列を入力してください:SEC SEC
文字列に含まれる特定文字の個数を返すプログラム
#include <stdio.h> /*--- 文字列str中の文字cの個数を返す ---*/ int str_chnum(const char str[], int c) { int i; int count = 0; for (i = 0; str[i] != '\0'; i++) if (str[i] == c) count++; return (count); } int main(void) { char str[256]; char ch[10]; printf("文字列を入力してください:"); scanf("%s", str); printf("検索する文字を入力してください:"); scanf("%s", ch); printf("その文字は%d個含まれています。\n", str_chnum(str, ch[0])); return (0); }
実行結果
文字列を入力してください:opqrst 検索する文字を入力してください:r その文字は1個含まれています。
文字列に特定文字が含まれているかどうかを調べるプログラム
#include <stdio.h> /*--- 文字列strから文字cを検索し、最も先頭側の要素の添字を返す ---*/ int str_char(const char str[], int c) { int i; for (i = 0; str[i] != '\0'; i++) if (str[i] == c) return (i); return (-1); } int main(void) { int no; char ch[10]; printf("英文字を入力してください:"); scanf("%s", ch); no = str_char("ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz", ch[0]); if (no >= 0 && no <= 25) printf("それは英大文字の%d番目です。\n", no + 1); else if (no >= 26 && no <= 51) printf("それは英小文字の%d番目です。\n", no - 25); else printf("それは英文字ではありません。\n"); return (0); }
実行結果
英文字を入力してください:E それは英大文字の5番目です。
文字列の配列を用意し、標準入力から読み込んだ文字列を表示するプログラム
#include <stdio.h> int main(void) { int i; char cs[3][128]; // 各文字列は最大128文字を格納 for (i = 0; i < 3; i++) { printf("cs[%d]:", i); scanf("%s", cs[i]); } for (i = 0; i < 3; i++) printf("cs[%d]=\"%s\"\n", i, cs[i]); return (0); }
実行結果
cs[0]:BS cs[1]:Window cs[2]:holiday cs[0]="BS" cs[1]="Window" cs[2]="holiday"
2次元配列に格納した文字列を表示するプログラム
#include <stdio.h> int main(void) { int i; char cs[][5] = {"LISP", "C++", "Ada"}; for (i = 0; i < 3; i++) printf("cs[%d]=\"%s\"\n", i, cs[i]); return (0); }
実行結果
cs[0]="LISP" cs[1]="C++" cs[2]="Ada"