0

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
                }

            }
info perto
  • 89
  • 1
  • 1
  • 11

2 Answers2

1

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();
payo
  • 4,501
  • 1
  • 24
  • 32
  • actually there is no list of words K cannot contain.It all about K itself.I will give another example.If K={"car","cars","cab"} then new K should {"car","cab"} because car is the root of cars – info perto May 16 '16 at 19:06
0

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.