我是C#的新手,只是在学习它。我相信你会认为这个问题很愚蠢,但我真的不明白下面提到的方法中出现以下问题的真正原因:
public static bool CheckIfCharactersAreDigits (string raw)
{
string s = raw.Trim();
if (s.Length == 0) return false;
for (int index = 0; index <= s.Length; index++)
{
if (char.IsDigit(s[index]) == false) return false;
}
return true;
}
在for循环中,我这样写表达式:index<=s.length?无论我输入什么字符或数字,它都会给我一个错误。错误为IndexOutOfRange。当我这样写这个表达式时:index<s.长度;那么一切都很好。但为什么呢?例如:我输入100作为字符串raw的参数,它的索引是[0,1,2]或3。如果index等于字符串raw的任何参数(只包含空格的除外(,为什么会出错
如果它让你感到困扰,我会通过Console.ReadLine((获得字符串原始值的参数,如果它在某种程度上有价值的信息(对此不确定(。
提前感谢您的任何建议!这真的很困扰我…
您正在对一个索引进行多次迭代。例如,如果数组的大小为10,则最后一项的索引将为9。
所以你需要从改变你的循环条件
index <= s.Length
至
index < s.Length
因此,对于数组的循环(以及其他标准集合(,应该总是这样:
for (int i = 0; i < array.Length; i++)
{
}
为了消除令人讨厌的范围外错误(此处为index <= s.Length
而非index < s.Length
(。
在Linq:的帮助下,尝试查询
using System.Linq;
...
public static bool CheckIfCharactersAreDigits (string raw)
{
//DONE: public method arguments validation (note null case)
if (string.IsNullOrWhiteSpace(raw))
return false;
return raw.Trim().All(c => char.IsDigit(c));
}
或者使用foreach
循环:让.net为您完成所有索引工作:
public static bool CheckIfCharactersAreDigits (string raw)
{
//DONE: public method arguments validation (note null case)
if (string.IsNullOrWhiteSpace(raw))
return false;
foreach (char c in raw.Trim())
if (!char.IsDigit(c))
return false;
return true;
}