使用lastIndexOf()时ArgumentOutOfRangeException

Dav*_*amp 2 c# substring lastindexof

我真的很难过为什么我得到一个例外.这是我组建的SSCCE来证明:

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);
}
Run Code Online (Sandbox Code Playgroud)

我无法看到我做错了什么(尽管来自Java背景可能是微不足道的),希望其他人可以.

jue*_*n d 5

substring第二个参数是要提取的字符串的长度,而不是字符串中的位置.

你可以做到

string intptr = tmp.Substring(one + 1, two - one - 1);
Run Code Online (Sandbox Code Playgroud)