0

I know this topic name is similar to another topic but that topic doesn't have the answers i wanted, so...

1st Question:

Let me say i have an array of:

string[] test = new string[5];
for(int x = 0; x <= test.Length - 1; x++)
{
    test[x] = "#" + (x + 1) + " element";
    Console.WriteLine(test[x]);
}

/*
output:
#1 element
#2 element
#3 element
#4 element
#5 element
*/

and say i wanted to remove "#4 element" from the string array, so that it instead outputs:

/*
output:
#1 element
#2 element
#3 element
#5 element
*/

how do i do that?

[PS:]The Answer i'm looking for is something that's easy to understand for a beginner.

Community
  • 1
  • 1
DerpyDog
  • 37
  • 7
  • 6
    It looks *remarkably* similar to [this question](http://stackoverflow.com/questions/496896/how-to-delete-an-element-from-an-array-in-c-sharp?rq=1). If you think it's different, please explain *how* your question is different. – Damien_The_Unbeliever Jul 17 '15 at 08:45
  • U can not do that in same array. U need to create the new one. For more info you can have a look on the link given by @demine. – Mudit Singh Jul 17 '15 at 08:51
  • @Kyle; Please check the answer – Tushar Jul 17 '15 at 08:51
  • Please check below post [Remove Element of a regular array][1] [1]: http://stackoverflow.com/questions/457453/remove-element-of-a-regular-array – arpan desai Jul 17 '15 at 08:51
  • @Damien_The_Unbeliever my question is different since i'm asking about `string`s instead of `int`s – DerpyDog Jul 17 '15 at 08:54
  • It is not relevant if the array type is string or int, just the same behaviour. Also your '2nd Question' is completely different and does not match your title. – Denis Thomas Jul 17 '15 at 09:00
  • @Denis i removed it, because i knew it was off-topic and that i already knew how to do that. – DerpyDog Jul 17 '15 at 09:02

8 Answers8

1

If you want to delete at particular index you can do as :

int[] numbers = { 1,2,3,4,5};
List<int> tmp = new List<int>(numbers);
tmp.RemoveAt(4);
numbers = tmp.ToArray();

But In your case since you are just expecting the element to be invisible and having the array length same :

string[] test = new string[5];
for(int x = 0; x <= test.Length - 1; x++)
{
    if(x!=3){
    test[x] = "#" + (x + 1) + " element";
    Console.WriteLine(test[x]);}
}
Tushar
  • 11,306
  • 1
  • 21
  • 41
0
  1. Use List<string> rather than an array.
  2. Use list.RemoveAt(3) to remove the forth element (elements start at 0)

So you might end up with something like the following in order to achieve you desired output:

var test = new List<string>();
for (var x = 1; x <= 5; x++)
{
    test.Add(String.Format("#{0} element", x));
}
Console.WriteLine(String.Join(" ", test);

test.RemoveAt(3);
Console.WriteLine(String.Join(" ", test);

Which will give you your desired output of:

#1 element #2 element #3 element #4 element #5 element

#1 element #2 element #3 element #5 element

David Arno
  • 40,354
  • 15
  • 79
  • 124
0

You cant just delete an Element from an array, you only can set it to "" for example.

Use List<string> instead.

TobiasR.
  • 788
  • 9
  • 19
0

1st Ans:

You can use list or if you dont want to use list use Linq but it will create a different memory location for array and will store elements there(I suppose). You can implement linq on your array as below:

test = test.Where(x => !x.Equals("#4 element")).ToArray();
//Print test Now

and now test array does not have "#4 element".

2nd Ans Instead of Console.WriteLine use Console.Write .

ATP
  • 551
  • 1
  • 3
  • 16
0

For your edit. While flushing your o/p just do not flush the outdated element. Using some conditional operator.

Eg: 1. If you want to remove on the basis of array valve then use

string[] test = new string[5];
for(int x = 0; x <= test.Length - 1; x++)
{
    test[x] = "#" + (x + 1) + " element";
    If (test[x] == "Desired value which you dont want to show")
    Console.WriteLine(test[x]);
}
  1. If you want to remove on the basis of array position then use

    string[] test = new string[5];
    for(int x = 0; x <= test.Length - 1; x++)
    {
        test[x] = "#" + (x + 1) + " element";
        If (x == "Desired index which you dont want to show")
           Console.WriteLine(test[x]);
    }   
    
Mudit Singh
  • 155
  • 1
  • 10
0

While what the others wrote is correct, sometimes you have an array, and you don't want to have a List<>...

public static void Main()
{
    string[] test = new string[5];

    for(int x = 0; x < test.Length; x++)
    {
        test[x] = "#" + (x + 1) + " element";
        Console.WriteLine(test[x]);
    }

    Console.WriteLine();

    RemoveAt(ref test, 3);
    // Or RemoveRange(ref test, 3, 1);

    for(int x = 0; x < test.Length; x++)
    {
        Console.WriteLine(test[x]);
    }
}

public static void RemoveAt<T>(ref T[] array, int index)
{
    RemoveRange(ref array, index, 1);
}

public static void RemoveRange<T>(ref T[] array, int start, int count)
{
    if (array == null)
    {
        throw new ArgumentNullException("array");
    }

    if (start < 0 || start > array.Length)
    {
        throw new ArgumentOutOfRangeException("start");
    }

    if (count < 0 || start + count > array.Length)
    {
        throw new ArgumentOutOfRangeException("count");
    }

    if (count == 0)
    {
        return;
    }

    T[] orig = array;
    array = new T[orig.Length - count];
    Array.Copy(orig, 0, array, 0, start);
    Array.Copy(orig, start + count, array, start, array.Length - start);
}

Two simple methods to remove elements of an array (RemoveAt and RemoveRange), with full example of use.

xanatos
  • 102,557
  • 10
  • 176
  • 249
0

Arrays have fixed size, so if you want add or remove element from them you need to deal with resizing. Therefore in C# it is recommended to use Lists instead (they deal with it themselves).Here is nice post about Arrays vs Lists.

But if you really want to do it with Array or have a reason for that, you could do it this way:

class Program
{
    static void Main(string[] args)
    {

        int[] myArray = { 1, 2, 3, 4, 5 };

        //destination array
        int[] newArray = new int[myArray.Length-1];

        //index of the element you want to delete
        var index = 3;

        //get and copy first 3 elements
        Array.Copy(myArray, newArray, index);

        //get and copy remaining elements without the 4th
        Array.Copy(myArray, index + 1, newArray, index, myArray.Length-(index+1));


        //Output newArray
        System.Text.StringBuilder sb = new System.Text.StringBuilder(); 
        for (int i = 0; i < newArray.Length; i++)
        {
            sb.Append(String.Format("#{0} {1}", i + 1, newArray[i]));                        
            if (!(i == newArray.Length - 1))
            {
                sb.Append(", ");
            }
        }
        Console.Write(sb.ToString());

        Console.ReadLine();

    }
Community
  • 1
  • 1
Weronika
  • 56
  • 4
0

See My solution... let me know if does helps...

class Program
    {

        // this program will work only if you have distinct elements in your array

        static void Main(string[] args)
        {
            string[] test = new string[5];
            for (int x = 0; x <= test.Length - 1; x++)
            {
                test[x] = "#" + (x + 1) + " element";
                Console.WriteLine(test[x]);

            }
            Console.ReadKey();
            Program p = new Program();
            test = p.DeleteKey(test, "#3 element"); // pass the array and record to be deleted
            for (int x = 0; x <= test.Length - 1; x++)
            {
                Console.WriteLine(test[x]);
            }
            Console.ReadKey();
        }

        public string[] DeleteKey(string[] arr, string str)
        {
            int keyIndex = 0;
            if (arr.Contains(str))
            {
                for (int i = 0; i < arr.Length - 1; i++)
                {
                    if (arr[i] == str)
                    {
                        keyIndex = i; // get the index position of string key
                        break; // break if index found, no need to search items for further
                    }
                }

                for (int i = keyIndex; i <= arr.Length - 2; i++)
                {
                    arr[i] = arr[i+1]; // swap next elements till end of the array
                }
                arr[arr.Length - 1] = null; // set last element to null

                return arr; // return array
            }
            else
            {
                return null;
            }
        }
    }
Mayur A Muley
  • 51
  • 1
  • 11