Страницы

Translate

пятница, 6 сентября 2013 г.

Exercise 5.5. Write versions of the library functions strncpy, strncat, and strncmp.

Exercise 5.5. Write versions of the library functions strncpy, strncat, and strncmp, which operate on at most the first n characters of their argument strings. For example, strncpy(s,t,n) copies at most n characters of t to s.

/* strncpy */
void strncpy(char *t, char *s, int n)
{
    while(n-- && *t)
            *t++ = *s++;
    while(*t)
        *t++='\0';
}

/* strncat */
void strncat(char *t, char *s, int n)
{
    while(*t)
        t++;
    while(*s && n--)
        *t++ = *s++;
    *t = '\0';
}


/* strncmp */
int strncmp(char *t, char *s, int n)
{
    for(;*t == *s && n > 0; t++, s++, n--)
        ;
    if(n == 0)
        return 0;
    else if(*t == '\0' && *s)
        return -1;
    else if(*t && *s == '\0')
        return 1;
    else
        return *t - *s;
}

Комментариев нет:

Отправить комментарий