我正在制作一个程序,该程序从用户那里获取 2 个字符串,然后从第一个字符串中删除第二个字符串的出现。
程序说明: 第二个字符串定义为包含字母、特殊字符、数字甚至空格的任何字符串,这些字符串可能存在也可能不存在于原始字符串中。它也可以在同一个输入字符串中出现多次。
我可以有长达 100 个字符的字符串。
1)一个接一个地从用户那里获取输入字符串,直到输入换行符。
2)我想编写一个函数来检查第一个模式字符串的出现,然后从第一个中删除它。
3)如果我确实找到了一个字符串,则返回 1,否则返回 0。如果存在,它将打印结果字符串,并删除字符。
这是我的代码:
#include <stdio.h>
#define STRING_SIZE 100
int remover(char *s1, char *s2, char *s3)
{
int i = 0, j, k,t=0;
while (s1[i])
{
for (j = 0; s2[j] && s2[j] == s1[i + j]; j++);
if (!s2[j])
{
for (k = i; s1[k + j]; k++)
s1[k] = s1[k + j];
s1[k] = 0;
s3[t]=s1[k + j];
t++;
}
else
i++;
}
if(strlen(s2)>1){
return 1;
}
return 0;
}
int main() {
char result_string[STRING_SIZE];
char MainString[STRING_SIZE], PatternString[STRING_SIZE];
printf("Please enter the main string..\n");
fgets(MainString,STRING_SIZE,stdin);
printf("Please enter the pattern string to find..\n");
fgets(PatternString,STRING_SIZE,stdin);
int is_stripped = remover(MainString,PatternString,result_string); // Your function call here..
printf("> ");
printf(is_stripped ? result_string : "Cannot find the pattern in the string!");
return 0;
}
它不起作用:(
正确输出的一些示例:
Please enter the main string..
This is an example string.
Please enter the pattern string to find..
ple str
>This is an examing.
Please enter the main string..
This is an example input string.
Please enter the pattern string to find..
Bazinga
>Cannot find the pattern in the string!
Please enter the main string..
A string is string.
Please enter the pattern string to find..
str
>A ing is ing.
**In this case, the pattern string was empty:**
Please enter the main string..
This is an example input string.
Please enter the pattern string to find..
>Cannot find the pattern in the string!
**In this case, the input was whitespace:**
Please enter the main string..
This is an input. This is after period.
Please enter the pattern string to find..
Thisisaninput.Thisisafterperiod.