C# 将月份转换为数字以用于排序算法-可能存在数组限制?

C# 将月份转换为数字以用于排序算法-可能存在数组限制?,c#,arrays,algorithm,sorting,C#,Arrays,Algorithm,Sorting,作为我为其中一项作业创建的程序的一部分,有一个文本文件,其中列出了月份(准确地说是600个月),这些月份必须按时间顺序排序,而没有内置的排序方法。导入月份并将其转换为数字并没有问题,但是输出数字数组的内容只输出数字6、11和12,然后才输出0。我认为这可能是数组大小的限制,但它不能解释为什么只输出3个数字 代码: static void Main(字符串[]args){ WriteLine(“未排序数组:”); 字符串[]monArray=File.ReadAllLines(“Month_1.t

作为我为其中一项作业创建的程序的一部分,有一个文本文件,其中列出了月份(准确地说是600个月),这些月份必须按时间顺序排序,而没有内置的排序方法。导入月份并将其转换为数字并没有问题,但是输出数字数组的内容只输出数字6、11和12,然后才输出0。我认为这可能是数组大小的限制,但它不能解释为什么只输出3个数字

代码:

static void Main(字符串[]args){
WriteLine(“未排序数组:”);
字符串[]monArray=File.ReadAllLines(“Month_1.txt”);
int[]numArray=新的int[12]{1,2,3,4,5,6,7,8,9,10,11,12};
int[]monthNums=新的int[monArray.Length];
int计数器=0;
对于(inti=0;i
问题在于,您正在将
月[counter]
赋值给相应的
numaray
中的值,并且每次迭代都要递增
计数器,因此它将递增600倍

我认为您真正想要做的是从
numArray
查找要更新的月份索引,然后在
monthNums
中向该项目的值添加一个索引,这可以使用
++
操作符完成

另外,请记住,数组是基于
0
的,这意味着at索引
[0]
中的第一项。您的
数组有
12个
项,这些项将是索引
0
-
11

// Initialize the array starting at '0', not '1'...
int[] numArray = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };

// For any given month string, look up it's corresponding index in numArray
// And use that value for the index to increment the count in monthNums
switch (month)
{         
    case "January":
        monthNums[numArray[0]]++;
        break;
    case "February":
        monthNums[numArray[1]]++;
        break;
    case "March":
        monthNums[numArray[2]]++;
        break;

    // continue this pattern...
}
另外,由于
numArray
中每个项目的值都是它的索引,因此您实际上不需要这个数组-您只需要
monthNums

switch (month)
{
    case "January":
        monthNums[0]++;
        break;
    case "February":
        monthNums[1]++;
        break;
    case "March":
        monthNums[2]++;
        break;

    // Continue this pattern ...
}

更好的解决方案可能是为月份创建一个
enum
,其中每个月的值对应于您要更新的索引,然后您可以使用
enum.TryParse
来获取索引。默认情况下,枚举中的第一项是
0
,之后的每个项都以
1
的增量递增,因此我们不需要这样做d显式分配枚举中的任何值

枚举看起来像:

enum Month
{
    January, February, March, April, May, June, July,
    August, September, October, November, December
}
然后你可以这样解析它:

foreach (string month in monArray)
{
    Month convertedMonth;

    // If the value of 'month' from our string array can be converted to a Month, 
    // update the count in the corresponding array index
    if (Enum.TryParse(month, true, out convertedMonth))
    {
        monthNums[(int)convertedMonth]++;
    }
}
下面是一个程序的工作示例,该程序使用600个随机月名填充数组(以模拟文件),然后使用每个月的计数更新第二个数组,最后输出结果:

private static void Main()
{
    // Populate our 'file' with 600 random month names:
    var rnd = new Random();
    var monArray = new string[600];
    for (int i = 0; i < 600; i++)
    {
        monArray[i] = ((Month) rnd.Next(0, 12)).ToString();
    }

    // The array to hold counts for each month
    int[] monthNums = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

    // Read each string, if it converts to a month, increment our counter
    foreach (string month in monArray)
    {
        Month convertedMonth;

        if (Enum.TryParse(month, true, out convertedMonth))
        {
            monthNums[(int) convertedMonth]++;
        }
    }

    // Output the counts for each month
    for (int i = 0; i < monthNums.Length; i++)
    {
        Console.WriteLine($"{(Month) i} count: {monthNums[i]}");
    }

    Console.Write("\nDone!\nPress any key to exit...");
    Console.ReadKey();
}

我不知道你到底在尝试什么,但似乎是这样的:

  • 阅读月份,一次一行,并将其转换为数字。
  • 这些数字应该方便地映射到数组的插槽1-12
  • 因此,请存储它们在此数组中出现的次数计数
  • 现在按顺序读取计数数组(即排序顺序),并希望将计数与顺序一起传递到输出
  • 在你做的事情中,我会避免做很多事情

  • 使您的代码可扩展到
  • 不同地区(非公历)(如适用)
  • 处理不区分大小写的输入
  • 处理短月份名称而不是完整月份名称
  • 不要使用case语句。尝试使用
    if
    语句或
    字典
    根据上述答案进行处理
  • 我对你对
    monthNums
    numaray
    所做的事情感到非常困惑。我认为
    numaray
    可能是多余的
  • 下面是我如何猜测一些需求并坚持您的想法来编写代码的

    static string[] MonthNames = new string[12]; // store the names of the month as found in the file to print out later
    
    static int GetMonthNumber(string month) {
        // Accommodating short month names and case sensitivity
        // TODO: handle locale issues for case and month names, if applicable
        var lowerMonth = month.ToLower();
        int value;
        if (lowerMonth.StartsWith("jan"))
            value = 0;
        else if (lowerMonth.StartsWith("feb"))
            value = 1;
        else if (lowerMonth.StartsWith("mar"))
            value = 2;
        else if (lowerMonth.StartsWith("apr"))
            value = 3;
        else if (lowerMonth.StartsWith("may"))
            value = 4;
        else if (lowerMonth.StartsWith("jun"))
            value = 5;
        else if (lowerMonth.StartsWith("jul"))
            value = 6;
        else if (lowerMonth.StartsWith("aug"))
            value = 7;
        else if (lowerMonth.StartsWith("sep"))
            value = 8;
        else if (lowerMonth.StartsWith("oct"))
            value = 9;
        else if (lowerMonth.StartsWith("nov"))
            value = 10;
        else if (lowerMonth.StartsWith("dec"))
            value = 11;
        else
            throw new ArgumentException($"Unknown month: {lowerMonth}", nameof(lowerMonth));
    
        MonthNames[value] = month;
    
        return value;
    }
    
    static void Main(string[] args) {
        Console.WriteLine("Unsorted Array:");
    
        string[] monArray = File.ReadAllLines("Month_1.txt"); /*new string[] { "January", "March", "January", "sept" };*/
    
        int[] monthNums = new int[11];
    
        for (int i = 0; i < monArray.Length; i++)
            Console.WriteLine(monArray[i]);
    
        foreach (string month in monArray)
            monthNums[GetMonthNumber(month)]++;
    
        for (int i = 0; i < monthNums.Length; i++) {
            if (monthNums[i] != 0)
                Console.WriteLine($"{MonthNames[i],-10} : ({monthNums[i]} times)");
        }
    
    }
    
    static string[]MonthNames=new string[12];//存储在文件中找到的月份名称,以便以后打印出来
    静态int GetMonthNumber(字符串月份){
    //适应短月份名称和区分大小写
    //TODO:处理案例和月份名称的区域设置问题(如果适用)
    var lowerMonth=月。ToLower();
    int值;
    if(从(“一月”)开始的最低月数)
    数值=0;
    否则,如果(最低月开始(“二月”))
    数值=1;
    否则,如果(最低开始时间(“mar”))
    数值=2;
    否则,如果(从最低月开始(“apr”))
    数值=3;
    否则,如果(最低开始时间(“五月”))
    数值=4;
    否则,如果(从(“六月”)开始的最低月数)
    数值=5;
    否则,如果(从(“七月”)开始的最低月数)
    数值=6;
    否则,如果(较低)
    
    enum Month
    {
        January, February, March, April, May, June, July,
        August, September, October, November, December
    }
    
    private static int ConvertMonthToInt(string month)
    {
        Month temp;
    
        if (!Enum.TryParse(month, true, out temp))
        {
            // Do something here if the string isn't a month
            return -1;
        }
    
        return (int)temp;
    }
    
    static string[] MonthNames = new string[12]; // store the names of the month as found in the file to print out later
    
    static int GetMonthNumber(string month) {
        // Accommodating short month names and case sensitivity
        // TODO: handle locale issues for case and month names, if applicable
        var lowerMonth = month.ToLower();
        int value;
        if (lowerMonth.StartsWith("jan"))
            value = 0;
        else if (lowerMonth.StartsWith("feb"))
            value = 1;
        else if (lowerMonth.StartsWith("mar"))
            value = 2;
        else if (lowerMonth.StartsWith("apr"))
            value = 3;
        else if (lowerMonth.StartsWith("may"))
            value = 4;
        else if (lowerMonth.StartsWith("jun"))
            value = 5;
        else if (lowerMonth.StartsWith("jul"))
            value = 6;
        else if (lowerMonth.StartsWith("aug"))
            value = 7;
        else if (lowerMonth.StartsWith("sep"))
            value = 8;
        else if (lowerMonth.StartsWith("oct"))
            value = 9;
        else if (lowerMonth.StartsWith("nov"))
            value = 10;
        else if (lowerMonth.StartsWith("dec"))
            value = 11;
        else
            throw new ArgumentException($"Unknown month: {lowerMonth}", nameof(lowerMonth));
    
        MonthNames[value] = month;
    
        return value;
    }
    
    static void Main(string[] args) {
        Console.WriteLine("Unsorted Array:");
    
        string[] monArray = File.ReadAllLines("Month_1.txt"); /*new string[] { "January", "March", "January", "sept" };*/
    
        int[] monthNums = new int[11];
    
        for (int i = 0; i < monArray.Length; i++)
            Console.WriteLine(monArray[i]);
    
        foreach (string month in monArray)
            monthNums[GetMonthNumber(month)]++;
    
        for (int i = 0; i < monthNums.Length; i++) {
            if (monthNums[i] != 0)
                Console.WriteLine($"{MonthNames[i],-10} : ({monthNums[i]} times)");
        }
    
    }