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

2009年(33)

我的朋友

分类: C/C++

2009-06-22 17:53:38

Exercise 2-4. Write an alternative version of squeeze(s1,s2) that deletes each character in s1 that matches any character in the string s2.
 

#include<stdio.h>

void squeeze(char *s1, const char *s2){
    int i, j, k;
    for(i = 0, j = 0; s1[j] != '\0'; j++){
        for(k = 0; s2[k] != '\0'; k++)
            if(s1[j] == s2[k])
                break;
        if(s2[k] == '\0')
            s1[i++] = s1[j];
    }
    s1[i] = '\0';
}

int main(){
    char s1[200], s2[100];
    scanf("%s", s1);
    scanf("%s", s2);
    squeeze(s1, s2);
    printf("%s\n", s1);
}

 
 
Exercise 2-5. Write the function any(s1,s2), which returns the first location in a string s1 where any character from the string s2 occurs, or -1 if s1 contains no characters from s2.(The standard library function strpbrk does the same job but returns a pointer to the
location.)
 

#include<stdio.h>

int any(const char *s1, const char *s2){
    int i, j;
    for(i = 0; s1[i] != '\0'; i++){
        for(j = 0; s2[j] != '\0'; j++)
            if(s1[i] == s2[j])
                return i;
    }
    return -1;
}

int main(){
    char s1[200], s2[100];
    int t;
    scanf("%s", s1);
    scanf("%s", s2);
    t = any(s1, s2);
    printf("%d\n", t);
}

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