ArgumentOutofBounds Exceptions is thrown all the times inside the ifs in the loop.
In this code I am trying to send two strings between the symbol @2@3.
string1+”@2@3″+string2
Now I try to separate the strings from the symbols by the method substring, but an exception is being thrown over there……
public void seperatePMChattersNames(string TwoNames)
{
string nameOne="";
string nameTwo="";
Console.WriteLine(TwoNames);
for (int i = 0; i < TwoNames.Length; i++)
{
if (TwoNames[i] == '2' && TwoNames[i-1] == '@')///ArgumentOutofRange Exception
{
nameOne = TwoNames.Substring(0, i);
}
if (TwoNames[i] == '@' && TwoNames[i+1] == '3')///ArgumentOutofRange Exception
{
nameTwo = TwoNames.Substring(i+1, TwoNames.Length);
}
}
}
Why is it thrown and how to prevent it?
When
iis zero,TwoNames[i - 1]will try to access index -1 of the string – that doesn’t exist.When
iisTwoNames.Length - 1,TwoNames[i + 1]will try to access past the end of the string.Next, when you have found “@3”, you’re using:
the second parameter of Substring is the length of the substring to take, not the final index. If you just want the rest of the string, you can omit the second argument:
Note that that would include the “3” though – so you probably really want i+2 instead of i+1.
Is there any reason you’re not using
string.IndexOf(TwoNames, "@2")etc?If you just want
nameOneto be the string before the first “@2” andnameTwoto be the string after the last “@3”, you can use:Another option is to use regular expressions, of course – they add a degree of complexity themselves, but they really are aimed at pattern matching. If you find you need to get even more bits and pieces, they could help.