【问题标题】:c # Exception index out of range [closed]c#异常索引超出范围[关闭]
【发布时间】:2013-10-19 04:11:18
【问题描述】:
public class Word
{
    private string _inputWord;
    public Word()
    {
        Console.WriteLine("Enter a word");
        _inputWord = Console.ReadLine();

    }

    public void sortandcount()
    {
        char[] test = _inputWord.ToCharArray();
        char temp;
        int count = 0, tcount = 0;
        Array.Sort(test);
        int length = test.Length;
        temp = test[0];

        while (length > 0)
            {
                for (int i = 0; i < test.Length; i++)
                {
                    if (temp == test[i])
                    {
                        count++;
                    }
                }
                Console.WriteLine(temp + " " + count);
                tcount = tcount + count;
                temp = test[tcount]; //this line 
                length = length - count;
                count = 0;
            }
        }



    }

    class Program
    {
        public static void Main() //this line 
        {
        Word obj = new Word();
obj.sortandcount();
        }
    }

我在两行出现异常,我在该行上表示为注释(如//程序中的这一行),你能帮我清除一下吗?该程序的 M 想法是计算给定单词中的字符数(相同)。 例如苹果 一个-1 p-2 l-1 e-1

【问题讨论】:

  • 尝试调试、单步调试代码并查看每个变量的值。这应该可以很容易地自己找出错误。
  • msdn.microsoft.com/en-us/library/…。请注意,数组是零索引的,这意味着最后一个元素索引是 Length-1。
  • @Kjartan 当然,我会尝试并在这里评论,感谢您的回复
  • 感谢您的帮助,我发现了我的错误并纠正了它@Kjartan,
  • @Ram 很高兴为您提供帮助! :)

标签: c# exception


【解决方案1】:

当您计算完所有字母后,tcount == test.length 这意味着 test[tcount] 将索引一个元素到 0 远。

给定任何数组 arr,那么 arr[arr.length] 将始终超出范围,因为 arr 是零索引的。在 temp = test[tcount] 之前,您需要确保 tcount &lt; test.length 但是您的逻辑也有错误

尝试使用单词obo,它将打印o 2 o 2

计算单词中字符的简单实现(如果顺序不必与单词中出现的相同)将是

var result = test.Aggregate(new Dictionary<char,int>(), (state,c)=>{
                if(!state.ContainsKey(c)) { state.Add(c,0); }
                state[c] += 1;
                return state;
             });

foreach(var pair in result) { Console.WriteLine(pair.Key + " " + key.Value); }

编辑如果您需要按照它们在单词中出现的顺序对它们进行排序,然后将 foreach 更改为此

foreach(var pair in result.OrderBy(p=>test.IndexOf(p.Key))) {
   Console.WriteLine(pair.Key + " " + key.Value);
}

【讨论】:

  • 如果订单应该和输入一样出现怎么办
【解决方案2】:

如果你想输出一个单词的字母数,试试这个代码:

var testString = "APPLE";

testString.ToCharArray()
.OrderBy(i => i).ToLookup(i => i)
.Select(i => new { letter = i.Key, count = i.Count() }).ToList()
.ForEach(i => Console.WriteLine("letter {0}, count {1}", i.letter, i.count));

这样更简洁,更不容易出错。

【讨论】:

    【解决方案3】:

    代码包含一个错误

     int length = test.Length; // This is not zero based
    

    并且计数从零开始,您的循环将执行一次额外的迭代,导致

     temp = test[tcount]
    

    失败,因为 tcount 现在比 test 的长度大 1 个字符。

    最好的办法是

    int length = test.Length -1;
    

    如果这有帮助,请告诉我:) 祝你有美好的一天

    【讨论】:

    • 我刚刚添加了这个 if 条件,所以再解决一个迭代问题,感谢帮助我 if (tcount!=test.length) temp = test[tcount];
    • 太棒了 ^^ 很高兴你提出了解决方案
    【解决方案4】:

    更“程序化”的版本:

    public class Word
    {
        private string _inputWord;
        public Word()
        {
            Console.WriteLine("Enter a word");
            _inputWord = Console.ReadLine();
        }
    
        public void SortAndCount()
        {
            // sort
            char[] array = _inputWord.ToCharArray();
            Array.Sort(array);
            // for all characters
            for(int i = 0; i < array.Length; i++)
            {
                // duplicate check
                if(i > 0 && array[i] == array[i - 1])
                    continue;
                // count
                int count = 0;
                for(int j = 0; j < array.Length; j++)
                    if(array[i] == array[j])
                        count++;
                Console.WriteLine(array[i] + " " + count);
            }
       }
    }
    
    class Program
    {
        public static void Main()
        {
            Word obj = new Word();
            obj.SortAndCount();
        }
    }
    

    【讨论】:

    • 你的代码比我的更易读。但是使用两个 for 循环需要比需要更多的迭代,所以我去了 while。
    • @Ram,添加了重复检查。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-16
    • 1970-01-01
    • 1970-01-01
    • 2012-02-09
    相关资源
    最近更新 更多