我想用c语言编写代码来删除字符串s1中与字符串s2中的任何字符匹配的任何字符。仅使用 for 循环。那就是我的试验失败了-_-。 例如,如果 s1="ahmed"和 s2="omnia"应将 s1 编辑为 >> s1="hed"
#include <stdio.h>
#include <stdlib.h>
int i,j;
int k;
int counter=0;
int main()
{
char s1[100];
char s2[10];
char temp[100];
printf("\n enter string 1: ");
scanf("%s",s1);
printf("\n enter string 2: ");
scanf("%s",s2);
printf("\n%s",s1);
printf("\n%s",s2);
for(j=0;j<9;j++)
{
for(i=0;i<9;i++)
{
if(s1[i]!=s2[j]&&s1[i]!='\0')
{
temp[counter++]=s1[i]; //add unique items to temp
k=counter; //size
temp[counter]='\0';
}
}
}
for(i=0;i<k;i++)
{
s1[i]=temp[i];
}
printf("\nstring 1 after delete : ");
printf("%s",s1);
return 0;
}
如何将一个项目与嵌套项目进行比较,然后达到某个条件?
最佳答案
为什么要在 if
中包含空字符语句陈述?
在两个 for
之后尝试这两个语句循环,像这样。 请缩进您的代码。
for(j=0;j<strlen(s1);j++) //Why is it 9 in your code? It should be the respective lengths
{
for(i=0;i<strlen(s2);i++)
{
if(s1[i]!=s2[j]&&s1[i]!='\0')
{
temp[counter++]=s1[i];
}
}
}
k=counter;
temp[counter]='\0';
并包括:#include<string.h>
关于c - 删除字符串中的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34295872/