C# 使用lastIndexOf()时ArgumentOutOfRangeException
我真的很困惑,为什么我会得到一个例外。以下是我为演示而制作的SSCCE:C# 使用lastIndexOf()时ArgumentOutOfRangeException,c#,substring,lastindexof,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.LastI
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);
}
static void Main(字符串[]args)
{
串tmp=
“查看可用网络的子对象(197314),标题:不适用(66244)”;
控制台写入线(tmp);
int one=tmp.LastIndexOf('('),two=tmp.LastIndexOf(');
//我自己的错误检查
Console.WriteLine(tmp.Length);//返回63
Console.WriteLine(一个<0);//返回false
Console.WriteLine(two>tmp.Length);//返回false
Console.WriteLine(一);//返回56
Console.WriteLine(二);//返回62
/*
*错误发生在这里。
*ArgumentOutOfRangeException索引和长度必须引用
*字符串中的位置。
*参数名称:长度
*/
字符串intptr=tmp.Substring(一,二);
控制台写入线(intptr);
}
我看不出我做错了什么(虽然来自Java背景,这可能很简单),希望其他人可以。第二个参数是要提取的字符串的长度,而不是字符串中的位置 你可以
string intptr = tmp.Substring(one + 1, two - one - 1);
string.Substring(startIndex,count)
您编写了startIndex和finishIndex,这是错误的您的代码
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>
string.Join(string.Empty,s.Skip(5.Take)(7-5+1))//从IEnumerable生成字符串
Thank you+1喜爱LINQ Part您如何将其转换回字符串?对不起,我是新来的:Pstringnewstr=tmp.Skip(一),Take(二-一)我真的需要更多的咖啡。再次修正,我总是忘记无数的警告。我正在整理一些评论。