[英]Remove string from string in C
我正在制作一个程序,该程序从用户那里获取 2 个字符串,然后从第一个字符串中删除第二个字符串的出现。
程序说明:第二个字符串定义为任何包含字母、特殊字符、数字甚至空格的字符串,这些字符串可能存在也可能不存在于原始字符串中。 它也可以在同一个输入字符串中出现多次。
我可以有长达 100 个字符的字符串。
1)一个接一个地从用户那里获取输入字符串,直到输入换行符。
2)我想写一个 function 来检查第一个模式字符串的出现,然后从第一个中删除它。
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;
}
它不起作用:(
对 output 的一些示例:
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.
char *strdelstr(char *s1, char *s2) {
char *loc = strstr(s1, s2);
if(loc != NULL)
strcpy(loc, loc + strlen(s2));
return s1;
}
这很容易。 但可能有更好的方法来做到这一点。
我稍微修改了你的代码。
int remover(char *s1, char *s2, char *s3)
{
int i = 0, j,t=0,found;
while (s1[i])
{
found=1;//Initilize found to true
for (j = 0;s2[j]!=0; j++){
if(s1[i+j]!=s2[j])
found=0;//Set not found
}
if(found==0){
s3[t]=s1[i];// if not found add char to s3.
t++;
}
else{
i=i+strlen(s2)-1;//if found skip
}
i++;
}
s3[t]=0;
if(strlen(s1)>strlen(s3)){
return 1;
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.