首页 > 编程语言 > 详细

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

时间:2014-03-20 21:28:49      阅读:647      评论:0      收藏:0      [点我收藏+]

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

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

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

 

bubuko.com,布布扣
#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;
}
bubuko.com,布布扣

 

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

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

C语言实现 字符串过滤并修改并返回个数,布布扣,bubuko.com

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

原文:http://www.cnblogs.com/xie-mx/p/3612590.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!