2

我真的很困惑为什么我会得到一个例外。这是我放在一起演示的 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);
}

我看不出我做错了什么(虽然来自 Java 背景可能是微不足道的),希望其他人可以。

4

3 回答 3

5

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

你可以做

string intptr = tmp.Substring(one + 1, two - one - 1);
于 2012-07-10T14:32:28.293 回答
2

你的代码

tmp.Substring(one, two);

应该

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

第二个参数是您想要的子字符串的长度,而我认为您正在使用它,就像它是结束索引一样。因为我喜欢 LINQ,所以也可以这样做:

string.Join(string.Empty, s.Skip(5).Take(7 - 5 + 1)); //build a string from IEnumerable<char>
于 2012-07-10T14:33:35.420 回答
1

string.Substring(startIndex, count ) 你写的 startIndex 和 finishIndex,错了

于 2012-07-10T14:32:59.590 回答