简体   繁体   中英

How to delete element from array?

I have an string array like this

K={"book","handbook","car"}

I would like to check if any string contains other string,if it does I would like to remove it from array .In the case of array K,new array should be like this

K="{"book","car"}

for (i = 0; i < 10; i++)
            {

                if (keywords.Contains(keywords[i])) { 

                      //I have no idea for this part
                }

            }

It might make more sense to use a List<> , a data structure designed for editing, whereas an array is a fixed structure. But, assuming you have an array, and need to end up with a modified array, you could convert:

IEnumerable<string> invalid_words = // ... list of words K cannot contain
string[] K = // .. array of strings you are given
K = K.Where(p => !invalid_words.Contains(p)).ToArray();

This might be a little "smelly" but it's better than try to modify the array when you are in an iteration.

The idea is this: save all the indexes where the word appears, and then erase those words. This is not the best solution, but it can help you with your problem. I highly recommends you to read about "Lists" because there are great on C# and it's easier use them than use arrays

K="{"book","car"};
//Never use a number, try to use the .length propertie
List<int> indexes=new List<int>();//using lists is easier than arrays
enter code here
for (i = 0; i < K.length; i++)
        {

            if (keywords.Contains(K[i])) 
            { 
                  //You save the index where the word is
                  indexes.add(i);
            }

        }
//Here you take those indexes and create a new Array
int[] theNewArray=new int[K.length-indexes.Count];
int positionInTheNewArray=0;
    for (i = 0; i < K.length; i++)
        {
         if(!indexes.Contains(i))
             {     theNewArray[positionInTheNewArray]=K[i];
                   positionInTheNewArray++;
             }
        }

}

That fits if your array allows duplicated words and also if duplicated words are not allowed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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