c - 从字符中删除字母并重新打印该字符

标签 c arrays string loops char

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/

相关文章:

c - 当输入无效时如何递归要求输入?

c - 关于scanf的一些问题

计算数组的数量

c# - 连接 SoundEffects (wav) 并保存到隔离存储

c - 字数统计问题

linux - Bash 字符串比较语法

c - 我将如何使用此 void 函数来计算百分比?

c - C中的char数组。如何找到有效输入的实际长度?

c# - 显示多个数组

regex - 在 elisp 中寻找替换字符串函数