Chinaunix首页 | 论坛 | 博客
  • 博客访问: 48027
  • 博文数量: 33
  • 博客积分: 1301
  • 博客等级: 中尉
  • 技术积分: 335
  • 用 户 组: 普通用户
  • 注册时间: 2008-08-31 21:06
文章分类
文章存档

2009年(33)

我的朋友

分类: C/C++

2009-06-03 23:37:28

Exercise 5-3
Write a pointer version of the function strcat that we showed in Chapter 2:
strcat(s,t) copies the string t to the end of s.
 

int pz_strcat(char *s1, char *s2){
    while(*s1)
        s1++;
    while(*s1++ = *s2++)
        ;
    return 1;
}
int main(){
    char s1[100];
    char s2[25];
    scanf("%s", s1);
    scanf("%s", s2);
    pz_strcat(s1, s2);
    printf("%s\n", s1);
    return 0;
}

 
Exercise 5-4. Write the function strend(s,t), which returns 1 if the string t occurs at the end of the string s, and zero otherwise.
 

int strend(const char *s1, const char *s2){
    int l1 = 0, l2 = 0;
    while(*s1){
        s1 ++;
        l1 ++;
    }
    while(*s2){
        s2 ++;
        l2 ++;
    }
    if(l1 < l2){
        return 0;
    }
    while(*--s1 == *--s2 && l2 > 0)
        l2 --;
    if(l2 == 0)
        return 1;
    else
        return 0;
}
int main(){
    char s1[50];
    char s2[25];
    scanf("%s", s1);
    scanf("%s", s2);
    if(strend(s1, s2))
        printf("yes!\n");
    else
        printf("no!\n");
}

 
Exercise 5-5. Write versions of the library functions strncpy, strncat, and strncmp, whichoperate 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. Full descriptions are in Appendix B.
 
 

void pzstrncpy(char *s1, const char *s2, int n){
    while(n > 0 && (*s1++ = *s2++))
        n --;
}

void pzstrncat(char *s1, const char *s2, int n){
    while(*s1)
        s1++;
    while(n > 0 && (*s1 = *s2)){
        n--;
        s1++;
        s2++;
    }
    if(*s1){
        *s1 = '\0';
    }
}

int pzstrncmp(char *s1, const char *s2, int n){
    while(n > 0 && *s1 == *s2){
        if(*s1 == '\0')
            return 0;
        s1++;
        s2++;
        n--;
    }
    if(n == 0)
        return 0;
    return *s1 - *s2;
}

int main(){
    char s1[100];
    char s2[100];
    scanf(" %s %s", s1, s2);
    int t = pzstrncmp(s1, s2, 5);
    if(t == 0)
        printf("=\n");
    else if(t > 0)
        printf(">\n");
    else
        printf("<\n");
}

阅读(257) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~