ここでは,次の標準ライブラリ関数の原本を見ます。
strcmp
strlen
strcpy
strrchr
* Copyright は原本に従います。但し,一部変更しています。
/* Example 18.1 */
#include <stdio.h>
#include <assert.h>
int my_strcmp (const char *, const char *);
int main(void)
{
int n;
char x[] = "test", y[] = "testing";
n = my_strcmp(x, y);
if (n)
printf("Distinct!\n");
else
printf("Match!\n");
return 0;
}
int
my_strcmp(s1, s2)
const char *s1, *s2;
{
assert (s1 != NULL);
assert (s2 != NULL);
while (*s1 == *s2++)
if (*s1++ == 0)
return (0);
return (*(const unsigned char *)s1 - *(const unsigned char *)--s2);
}
実行すると
Distinct!
と出力されます。strcmp 関数は文字列を比較します。ソース内の assert 関数は,ヘッダファイル assert.h に入っている関数で,引数が 0 のときエラーを標準エラー出力し,処理をやめます。(const unsigned char *) の () はキャスト演算子です。
/* Example 18.2 */
#include <stdio.h>
#include <assert.h>
size_t my_strlen (const char *);
int main(void)
{
char x[] = "testing";
printf("Number of letters = %zd\n", my_strlen(x));
return 0;
}
size_t
my_strlen(str)
const char *str;
{
const char *s;
assert(str != NULL);
for (s = str; *s; ++s);
return(s - str);
}
実行結果です。
Number of letters = 7
strlen関数は文字列の数を数えます。返却値型が size_t型ですが,実際は ptrdiff_t型で返しています。
/* Example 18.3 */
#include <stdio.h>
#include <assert.h>
char *my_strcpy (char *, const char *);
int main(void)
{
char x[10] = "testing";
char y[10];
char *z;
z = my_strcpy(y, x);
printf("Copied: %s (z: %s)\n", y, z);
return 0;
}
char *
my_strcpy(to, from)
char *to;
const char *from;
{
char *save = to;
assert(to != NULL);
assert(from != NULL);
for (; (*to = *from) != '\0'; ++from, ++to);
return(save);
}
実行結果です。
Copied: testing (z: testing)
strcpy 関数は文字列をコピーする関数で「9.3. 文字列の操作」で使用しました。ソースを読むと,第2変数から第1変数の大きさを無視してメモリに書き込む様子が見て取れると思います。次は,strrchr 関数です。
/* Example 18.4 */
#include <stdio.h>
#include <assert.h>
char *my_strrchr (const char *, int);
int main(void)
{
char str[] = "C@langauge@testing";
char key = '@';
char *y;
y = my_strrchr(str, key);
printf("Last segmented = %s\n", y);
return 0;
}
char *
my_strrchr(p, ch)
const char *p;
int ch;
{
char *save;
assert(p != NULL);
for (save = NULL;; ++p) {
if (*p == ch) {
save = (char *)p;
}
if (!*p)
return(save);
}
}
実行結果です。
Last segmented = @testing
strrchr 関数は,第1変数の文字列の中で第2変数で指定した文字が最後に現れたポインタを返します。