简体   繁体   English

如何从C中的字符串数组中删除字符串

[英]How to delete a string from an array of string in c

I have a multidimensional array in which i put words inside . 我有一个多维数组,在其中放置单词。 After , i ask the user to delete a word . 之后,我要求用户删除一个单词。 But it won't delete. 但不会删除。

#include<stdio.h>

void main ()
{

    int i ; 
    int nbr ;
    char n[50][50];
    char d[50];

    printf("Enter the number of word you want : \n");
    scanf("%d",&nbr);

    for(i=0; i < nbr ; i++)
    {
        printf("Enter words : \n");
        scanf("%s",&n[i]);  
    }

    printf("you have enter: \n");
    for(i = 0; i < nbr ; i++)
    {   
        printf("%s \n",n[i]);
    }


    printf("Wich word you want to remove  : ? \n");
    scanf("%s",&d);

    for(i=0; i < nbr ; i++)
    {
        if(strcmp(n[i],d)==0)
        {
            n[i] = n[i+1] ; 
            i-- ; 
        }
    }
    printf("The rest of array is : \n");
    scanf("%s",&n[i]);

}

[Error] assignment to expression with array type [错误]分配给具有数组类型的表达式

Although arrays are implemented with pointers in C, the compiler will treat them the differently. 尽管数组是使用C语言中的指针实现的,但是编译器将对它们进行不同的处理。 As you can see in your own example the line n[i] = n[i+1] causes the error you see, because n[i] is an array of chars. 正如您在自己的示例中看到的那样,行n [i] = n [i + 1]会导致您看到错误,因为n [i]是一个字符数组。

Even if you could make the assignment you wanted, the logic of your program still has an error. 即使可以进行所需的分配,程序的逻辑仍然有错误。 If you were able to succeed in your call to n[i] = n[i+1] you would effectively be duplicating whatever was in n[i+1] twice. 如果您能够成功调用n [i] = n [i + 1],那么您将有效地重复两次复制n [i + 1]中的任何内容。

Instead you likely want to copy n[i+1] into n[i], then copy n[i+2] into n[i+1] and so on. 相反,您可能想将n [i + 1]复制到n [i],然后将n [i + 2]复制到n [i + 1],依此类推。 This will be expensive, you may want to look into using a linked list instead, although this really depends on what else you want to do with this data structure. 这将很昂贵,您可能想使用链表,尽管这实际上取决于您要对该数据结构进行的其他操作。

 [Error] assignment to expression with array type 

In C an array can not be assigned. 在C中,无法分配数组。

You need to copy the content of the source array are into the destination array. 您需要将源数组的内容复制到目标数组中。

For the special case of a 0 -terminated char array (aka C-string) you can use the strcpy() function to do so: 对于以0结尾的char数组(又称C字符串)的特殊情况,可以使用strcpy()函数执行此操作:

    strcpy(n[i], n[i+1]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM