文字列の文字数をカウントする
コマンドラインで渡された引数は、とりあえずは文字列型として扱われる。この文字列を使っていろいろやることになりそうなので、文字列を扱う基本を抑えないと、ということで文字列を数えるやり方をメモ。string.h をインクルードして strlen 関数を使用すればいいだけだが。。。
#include <stdio.h> #include <string.h> int main(int argc, char *args[]){ if ( argc == 2 ) { printf("Command line argument \"%s\" length is %lu.\n", args[1], strlen(args[1])); } else { printf("Usage: %s $1\n", args[0]); } return 0; }
実行例。
$ gcc strlensample.c $ $ $ $ ./a.out 5 Command line argument "5" length is 1. $ ./a.out 5555 Command line argument "5555" length is 4. $ ./a.out 5555xxxxx Command line argument "5555xxxxx" length is 9. $