Search code examples
c#substringlastindexof

ArgumentOutOfRangeException when using lastIndexOf()


I'm really stumped as to why I'm getting an exception. Here is a SSCCE I put together to demonstrate:

static void Main(string[] args)
{
    string tmp =
               "Child of: View Available Networks (197314), Title: N/A  (66244)";
    Console.WriteLine(tmp);

    int one = tmp.LastIndexOf('('), two = tmp.LastIndexOf(')');

    //my own error checking
    Console.WriteLine(tmp.Length);//returns 63
    Console.WriteLine(one < 0);//returns false
    Console.WriteLine(two > tmp.Length);//returns false
    Console.WriteLine(one);//returns 56
    Console.WriteLine(two);//returns 62

    /*
     * error occurs here.
     * ArgumentOutOfRangeException Index and length must refer to
     * a location within the string.
     * Parameter name: length
     */
    string intptr = tmp.Substring(one, two);

    Console.WriteLine(intptr);
}

I can't see what I am doing wrong (though coming from a Java background it might be trivial), hopefully someone else can.


Solution

  • substrings 2nd parameter is the length of the string you want to extract and not the position in the string.

    You could do

    string intptr = tmp.Substring(one + 1, two - one - 1);