c # 异常索引超出范围
本文关键字:范围 索引 异常 | 更新日期: 2023-09-27 18:34:56
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();
}
}
我在两行中得到异常,我已指示为该行的评论(如程序中的//行(,您能帮我清除 abt 吗?程序的M想法是计算给定单词中的字符数(相同(。例如苹果A-1P-2L-1E-1
当你计算完所有字母后,tcount == test.length
这意味着test[tcount]
会将一个元素索引到0。
给定任何数组 arr,则arr[arr.length]
将始终超出界限,因为 arr 的索引为零。在 temp = test[tcount] 之前,您需要确保tcount < 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);
}
如果要
输出单词中的字母计数,请尝试以下代码:
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));
这更干净,更不容易出错。
代码包含一个错误
int length = test.Length; // This is not zero based
并且计数从零开始,您的循环将执行一次额外的迭代,从而导致
temp = test[tcount]
失败,因为 tcount 现在比测试长度大 1 个字符。
最好的办法是
int length = test.Length -1;
请让我知道这是否有帮助:)有好的一天
更"程序化"的版本:
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();
}
}