天天看點

C程式設計語言第二版習題2-4問題描述問題拆分代碼實作

問題描述

編寫函數squeeze(s1, s2), 把字元串s1中與字元串s2中字元比對的所有字元都删除。

問題拆分

  • 主函數main
  • 接收使用者輸入字元串函數 get_line (注意不能按照書本上的getline,因為此函數已在stdio.h 中定義了)
  • 從s1中移除s2中包含的字元 函數 squeeze

代碼實作

#include<stdio.h>

#define LINE 1000

int get_line(char s[]);
int squeeze(char s[], char search[]);

int main()
{
    char line[LINE];
    char search[LINE]; //要過濾的字元串 
    int len;

    printf("Type the search:\n");
    get_line(search); 
    printf("Type the subject:\n");
    while(len = get_line(line) > 0){
        squeeze(line, search);
        printf("The result is: %s \n", line);
    }
    return 0;
}

//接收一行字元串 
int get_line(char s[])
{
    int i;
    char c;

    for(i = 0; i < LINE - 1 && (c = getchar()) != EOF && c != '\n'; i++){
        s[i] = c;
    }
    s[i] = '\0';
    return i;
}

/*
 * 核心方法,從目标字元串移除指定字元 
 * 從subject中逐個剔除search中的字元 
 */
int squeeze(char subject[], char search[])
{
    int i, j, k;
    char c;
    k = 0;
    while((c = search[k++]) != '\0'){ //逐個移除 
        for(i = j = 0; subject[i] != '\0'; i++){
            if(subject[i] != c){
                subject[j++] = subject[i];
            }
        }
        subject[j] = '\0';
    }
    return 0;
}           

繼續閱讀