为什么这段代码在我运行时会给出索引超出范围的异常?
class stringcodetesting
{
static void Main(string[] args)
{
string t = " abcdefghigklmnopqrstuvwxyz" ;
string c;
char [] ar = { 'h', '1','2', '3','4'};
c = "aarsa";
Console.WriteLine(t[t.IndexOfAny(ar,0,6)]);
}
}但是,当string t value ="abcdefghigklmnopqrstuvwxyz" (字符串开头没有空格)正常工作时,没有任何异常。
发布于 2015-05-26 00:59:15
因为在t的前6个字符(.IndexOfAny(..., 0, 6))中,ar中没有出现任何字符。这也反映在-1的返回值中,这意味着没有找到匹配项。
发布于 2015-05-26 01:08:57
是的,上面已经回答了原因,但这里有一个解决方案。
If(t.IndexOfAny(ar,0,6) >= 0)
{
Console.WriteLine(t[t.IndexOfAny(ar,0,6)]);
}
Else
{
Console.WriteLine("No Match!");
}https://stackoverflow.com/questions/30442725
复制相似问题