Reputation: 47
Why this code gives index out of range exception when I run it ?
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)]);
}
}
but when the string t value ="abcdefghigklmnopqrstuvwxyz"
(without space in the beginning of the string ) it works correctly without exception.
Upvotes: 0
Views: 459
Reputation: 510
Yeah, already answered above as to the reason, but here is a solution.
If(t.IndexOfAny(ar,0,6) >= 0)
{
Console.WriteLine(t[t.IndexOfAny(ar,0,6)]);
}
Else
{
Console.WriteLine("No Match!");
}
Upvotes: 0
Reputation:
Because within the first 6 characters (.IndexOfAny(..., 0, 6)
) of t
there's no occurence of any of the characters in ar
. That is also reflected by the return value of -1
, which means no occurence found.
Upvotes: 3