2013年5月3日金曜日

開発環境

プログラミング言語C 第2版 ANSI規格準拠 (B.W. カーニハン D.M. リッチー (著)、 石田 晴久 (翻訳)、共立出版)の第5章(ポインタと配列)、5.5(文字ポインタと関数)、演習5-5を解いてみる。

その他参考書籍

演習 5-5.

コード

sample.c

#include <stdio.h>
#define SIZE 1000

void my_strncpy(char *s, char *t, int n);
void my_strncat(char *s, char *t, int n);
int my_strncmp(char *s, char *t, int n);

int main()
{
    char s[SIZE], s1[SIZE];
    char t[] = "Hello, World!";
    int i;
    
    printf("strncpy\n");
    printf("%s\n", t);

    for (i = 0; i < 15; i++) {
        my_strncpy(s, t, i);
        printf("%s\n", s);
    }
    
    printf("strncat\n");
    for (i = 0; i < 15; i++) {
        s[0] = '\0';
        my_strncat(s, t, i);
        printf("%s\n", s);
    }
    
    printf("strncmp\n");
    for (i = 0; i < 5; i++)
         printf("%d\n", my_strncmp("", "", i));
    for (i = 0; i <= 6; i++)
        printf("%d\n", my_strncmp("abcde", "", i));
    for (i = 0; i <= 6; i++)
        printf("%d\n", my_strncmp("", "abcde", i));
    for (i = 0; i <= 6; i++)
        printf("%d\n", my_strncmp("abcde", "ab", i));
    for (i = 0; i <= 6; i++)
        printf("%d\n", my_strncmp("ab", "abcde", i));
    return 0;
}

void my_strncpy(char *s, char *t, int n)
{
    while (n-- > 0 && (*s++ = *t++))
        ;
    if (n < 0)
        *s = '\0';
}

void my_strncat(char *s, char *t, int n)
{
    while (*s != '\0')
        s++;
    while (n-- > 0 && (*s++ = *t++))
        ;
    if (n < 0)
        *s = '\0';
}

int my_strncmp(char *s, char *t, int n)
{
    for (; *s == *t; s++, t++)
        if (*s == '\0' || --n <= 0)
            return 0;
    return *s - *t;
}

入出力結果(Terminal)

$ ./a.out
strncpy
Hello, World!

H
He
Hel
Hell
Hello
Hello,
Hello, 
Hello, W
Hello, Wo
Hello, Wor
Hello, Worl
Hello, World
Hello, World!
Hello, World!
strncat

H
He
Hel
Hell
Hello
Hello,
Hello, 
Hello, W
Hello, Wo
Hello, Wor
Hello, Worl
Hello, World
Hello, World!
Hello, World!
strncmp
0
0
0
0
0
97
97
97
97
97
97
97
-97
-97
-97
-97
-97
-97
-97
0
0
0
99
99
99
99
0
0
0
-99
-99
-99
-99
$

0 コメント:

コメントを投稿