Create new Array from old Array
Hey,
I have a String array with multiple elements in it and I want to create another String array from it but, I don't want to take all the elements from the first array, theres a criteria for it the strings length.
So Ive got an array with 10 elements in..
[1] = Eitens
[2] = Dietrumpream
[3] = Formal
[4] = and
[5] = Weide
[6] = Forma
[7] = Spreorphotes
[8] = the
[9] = Bly
[10] = Coming
and the new array will have the following conditions, each element cant be longer than 3 characters long, so the second array should be of size 3 with the elements "and","the","bly" and of course in the same order as they were?
This is what I've to so far:
Code :
int number = 0;
for (int i = 0; i < S1.length; i++)
{
if (S1[i].length() >= key.length())
{
number++;
}
}
String sorted[] = new String[number];
int j = 0;
for(int i = 0; i<S1.length;i++)
{
if (S1[i].length() <= key.length()){
sorted[j] = S1[i];
j++;
}
}
Where am I going wrong?
Re: Create new Array from old Array
You're putting the elements into the exact same spot as they were in the original array. What you should be doing is using a separate counter to determine where to put the elements. This won't change the fact that you're array will have a bigger size still. There are two possible solutions: use an ArrayList, which will keep track of the size for you, or re-allocate a third array to the number of elements you want to keep after you've found all of them and transfer them over.