marcus.x的博客

C语言实现 字符串过滤并修改并返回个数

基本问题:给定一个strContent,strWord,使用strWord 匹配strContent,匹配成功,将匹配部分全部替换为‘*’ ,并返回匹配成功个数。注意不能使用库函数。

 例如:strContent = "today is sunday."  strWord = "day"  那么应该返回2,而且strContent变成 "to*** is sun***."

问题不难,但是对我来说有些考验。

 

#include <stdlib.h>
#include <stdio.h>
#include <string.h> // 用来测试,输入数据用的,题目要求不能使用库函数

int filter(char *strContent, char *strWord)
{
    int count = 0;
    char *p = strContent;
    char *s = strWord;
    if (p == NULL || s == NULL)
        exit(1);    
    while(*p != '\0')
    {
        char *p1 = p;
        s = strWord;
        for(;*p1 == *s && *s!= '\0';p1++,s++);
        if (*s == '\0')
        {
            count++;
            s = strWord;
            while(*s++ != '\0') *--p1 = '*';
        }
        if (*p1 == '\0')    
        {
            break;
        }    
        p++;
    }
    return count;
}

int main(int argc, char *argv[])
{
    char *strContent = (char *) malloc(20);
    char *strWord = (char *) malloc(20);
    strcpy(strContent, argv[1]);
    strcpy(strWord, argv[2]);
    int result = filter(strContent, strWord);
    printf("result : %d\n", result);
    printf("strContent : %s\n", strContent);
    return 0;
}

 

我的方法很笨,想了很久,才能够完成,真的是惭愧。

如果有更好的办法,求指教。

posted on 2014-03-19 23:05  marcus.x  阅读(796)  评论(0编辑  收藏  举报

导航