【发布时间】:2015-06-05 12:36:54
【问题描述】:
我正在尝试从字符串的最后一部分中提取数字,我已经编写了一个函数来执行此操作,但遇到超出范围索引的问题。
这是字符串
type="value" cat=".1.3.6.1.4.1.26928.1.1.1.2.1.2.1.1" descCat=".1.3.6.1.4.1.26928.1.1.1.2.1.2.1.3"
这是我的功能
private static string ExtractDescOID(string property)
{
string result = "";
int startPos = property.LastIndexOf("descOid=\"") + "descOid=\"".Length;
int endPos = property.Length - 1;
if (endPos - startPos != 1)
{
//This now gets rid of the first . within the string.
startPos++;
result = property.Substring(startPos, endPos);
}
else
{
result = "";
}
if (startPos == endPos)
{
Console.WriteLine("Something has gone wrong");
}
return result;
}
我希望能够得到1.3.6.1.4.1.26928.1.1.1.2.1.2.1.3这部分字符串。我已经通过代码,字符串长度是 99 但是当我的 startPos 变为 64 并且 endPos 变为 98 时,实际上在范围内。
【问题讨论】:
-
Substring()采用起始索引和长度,64 + 98 > 99 -
您尝试获取
descOid=的起始索引,但它不是您的字符串的一部分。还是我瞎了?