【问题标题】:Delete a number from Array in C#C#从数组中删除一个数字
【发布时间】:2020-08-17 12:09:10
【问题描述】:

我正在尝试从数组中删除一个数字。我试过按照教程进行操作,该方法会删除我输入的数字,如果有重复,它会删除第一个重复的数字,但是它总是在开始时显示 0,即使 0 不是数组中的数字。例如。假设我有一个数字列表 1, 12, 44, 55, 66, 17, 8, 4, 12, 70,我删除数字 44,输出为:0, 1, 12, 55, 66, 17, 8, 4、12、70。我不知道为什么会出现 0 以及如何摆脱它。任何帮助将不胜感激。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace deletenumber
{
class Program
{
    public class Node
    {
        public int data;
        public Node next;
    };

    static Node add(Node head, int data) 
    {
        Node temp = new Node();
        Node current;
        temp.data = data;
        temp.next = null; 

        if (head == null) 
            head = temp;
        else
        {
            current = head;
            while (current.next != null)
                current = current.next;
            current.next = temp; 
        }
        return head;
    }

    static void print(Node head)
    {
        while (head != null) 
        {
            Console.Write(head.data + " "); 
            head = head.next;
        }
    }

    static Node List(int[] a, int n)
    {
        Node head = null; 
        for (int i = 1; i <= n; i++)
            head = add(head, a[i]);
        return head;
    }

    public static void Main(String[] args)
    {
        int n = 10;
        Random r = new Random(); 
        int[] a;
        a = new int[n + 1];
        a[0] = 0;
        int i;

        for (i = 1; i <= n; i++)
            a[i] = r.Next(1, 100);

        Node head = List(a, n);
        Console.WriteLine("List = ");

        print(head);
        Console.ReadLine();
        Console.WriteLine();

        Console.WriteLine("What number do you want to delete?");
        int item = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine();

        int index = Array.IndexOf(a, item);
        a = a.Where((e, k) => k != index).ToArray();

        Console.WriteLine(String.Join(", ", a));
        Console.ReadLine();
    }
 }
}

【问题讨论】:

  • a[0] = 0;在静态主目录中?
  • 如果我不迷茫,你把a[0] = 0,并没有覆盖它
  • a[0] = 0; - 你的数组总是有那个零......但是在你的 List 函数中,你从索引 1 开始,所以你第一次看不到“0”(当你调用print(head),但您确实稍后将数组转储到控制台时会看到它
  • 但是我如何改变它,使它不显示 0

标签: c# arrays linked-list


【解决方案1】:

如果您不想打印0,我不知道您为什么要首先添加它,但请注意您“打印”数组的两种不同方式。

第一个方法(print 函数)从第 1 项开始(跳过索引 0 处的“第一个”元素)并循环直到结束。

数组的第二个刚刚joins 所有元素(包括“第一个”元素)并打印结果字符串。

那么你如何跳过零?方法有很多:

  • 首先不要添加零(并将您的 print 循环更改为从 0 开始)

  • 使用从 1 开始循环的相同打印方法

  • Skip 数组中的第一项:

    Console.WriteLine(String.Join(", ", a.Skip(1)));
    

就我个人而言,我只会使用相同的方法打印两次,我也会使用Array.RemoveAt 来“删除”项目,而不是使用Where().ToArray() 创建一个新数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-08
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 2021-07-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多