main(void)
{
int p;
char n[6]="apple";
char n2[6]="happy";
for(int i=0;i<6;i++)
{
for (int j=0;j<6;j++)
{
if(n[i]==n2[j])
// I want n2[j] removed
printf("%c",n2[j]);
break;
}
}
}
我希望 n2[j] 从字符中删除。 示例:在本例中,n[0]=n2[1],即 a=a。我希望从单词中删除“a”。
最佳答案
这将打印要删除的字符,并将 n2[j] 之后的 n2 中的所有字符移动到(包括空终止符)后一个字节,包括空终止符。字符串长度是在每个循环上测量的,因此您不会循环超过第一个空终止符。 main() 也应该返回 int。
#include <stdio.h>
int main(void)
{
//char n[6] = "apple";
//char n2[6] = "happy";
char n[] = "abcdefghij";
char n2[] = "a1b2c3d4e5f6g7h8i9";
for (int i = 0; i < strlen(n); i++) // You shouldn't loop the size of the array
// but the size of the string, because
// you wouldn't want to remove the null
// terminator
{
for (int j = 0; j < strlen(n2); j++) // Same here
{
if (n[i] == n2[j])
{
printf("Removing char %c \n", n2[j]);
memmove(&n2[j], &n2[j + 1], strlen(n2) - j);
}
}
}
printf("\nn2 = %s", n2);
return 0;
}
如果要在删除后打印该字符,则只需打印 n[i],因为在“if” block 内 n[i] 保证为 n2[j]。
关于c - 从字符中删除字母并重新打印该字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49567953/