子串超出范围 [英] substring out of range

查看:24
本文介绍了子串超出范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从字符串的最后一部分中提取数字,我编写了一个函数来执行此操作,但在索引超出范围时遇到问题.

I am trying to extract the number out of the last part of the string, I have wrote a function to do this but am having problems with out of range index.

这是字符串

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,但是当 AND MY startPos 变为 64 并且 endPos 变为 98 时,实际上在范围内.

I want to be able to get 1.3.6.1.4.1.26928.1.1.1.2.1.2.1.3 this part of the string. I have stepped through the code, the string length is 99 however when AND MY startPos becomes 64 and endPos becomes 98 which is actually within the range.

推荐答案

Substring(int, int) 的第二个参数不是结束位置",而是子串的长度返回.

The second argument to Substring(int, int) isn't the "end position", but the length of the substring to return.

 result = property.Substring(startPos, endPos - startPos);

这篇关于子串超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆