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

时间:2023-03-08 21:30:42

基本问题:给定一个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 = ;
char *p = strContent;
char *s = strWord;
if (p == NULL || s == NULL)
exit();
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();
char *strWord = (char *) malloc();
strcpy(strContent, argv[]);
strcpy(strWord, argv[]);
int result = filter(strContent, strWord);
printf("result : %d\n", result);
printf("strContent : %s\n", strContent);
return ;
}

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

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