Hi, I got a question. I am trying to check if an array contains values of another array. How can I do this. I am trying to do it by using for and if, but could not do it. So,
int[] firstarray = new int[5];
int[] secondarray = new int[2]; // the length of second array may change in my program so it shoud be new int[length]
firstarray[0]=1;
firstarray[1]=2;
firstarray[2]=3;
firstarray[3]=4;
firstarray[4]=5;
secondarray[0]=1;
secondarray[1]=2;
int[] Resultarray =new int[5];
for (int i=0; i<5; i++)
{
if (firstarray[i]!=secondarray[0] && firstarray[i]!=secondarray[1]) //the problem is here since the length of secondarray may change, I can not check it like I do here.
Resultarray[i]=firstarray[i];
else Resultarray[i]=0;
}
I appriciate any help
Loading
kekPosted Mar 30, 2008, 9:05 PM
AlanPosted Mar 30, 2008, 7:15 AM
Try it like this. If I've understood it correctly, you want the result array to contain 0 if the corresponding element of the first array is present in the second array, but otherwise to contain the corresponding element of the first array. So, in the example, the resulting array should be {0,0,3,4,5}:
int[] firstArray = new int[5] {1,2,3,4,5};
int secondSize = 2; // or whatever
int[] secondArray = new int[secondSize];
for (int i = 0; i < secondArray.Length; i++)
{
secondArray[i] = i + 1; // say
}
int[] resultArray =new int[5];
for (int i=0; i<5; i++)
{
bool isPresent = false;
for (int j = 0; j < secondArray.Length; j++)
{
if (secondArray[j] == firstArray[i])
{
isPresent = true;
break;
}
}
if (!isPresent)
resultArray[i] = firstArray[i];
else
resultArray[i] = 0;
}