substring out of range

后端 未结 3 1310
Happy的楠姐
Happy的楠姐 2021-01-28 02:00

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.

Here is the stri

相关标签:
3条回答
  • 2021-01-28 02:14

    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);
    
    0 讨论(0)
  • 2021-01-28 02:14

    A different approach to this problem could be through using string.Split() to take care of the parsing for you. The only reason why I would propose this (other than that I like to present additional options to what's already there, plus this is the lazy man's way out) is that from a code perspective, the code is easier IMHO to decompose, and when decomposed, is easier to comprehend by others.

    Here's the sample program with some comments to illustrate my point (tested, btw).

    class Program
    {
        static void Main(string[] args)
        {
            var someAttributesFromAnXmlNodeIGuess = 
    "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\"";
    
            var descCat = GetMeTheAttrib(someAttributesFromAnXmlNodeIGuess, "descCat");
    
            Console.WriteLine(descCat);
            Console.ReadLine();
        }
    
        // making the slightly huge assumption that you may want to 
        // access other attribs in the string...
        private static string GetMeTheAttrib(string attribLine, string attribName)
        {
            var parsedDictionary = ParseAttributes(attribLine);
    
            if (parsedDictionary.ContainsKey(attribName))
            {
                return parsedDictionary[attribName];
            }
    
            return string.Empty;
        }
    
        // keeping the contracts simple - 
        // i could have used IDictionary, which might make sense 
        // if this code became LINQ'd one day
        private static Dictionary<string, string> ParseAttributes(string attribLine)
        {
            var dictionaryToReturn = new Dictionary<string, string>();
    
            var listOfPairs = attribLine.Split(' '); // items look like type=value, etc
            foreach (var pair in listOfPairs)
            {
                var attribList = pair.Split('=');
    
                // we were expecting a type=value pattern... if this doesn't match then let's ignore it
                if (attribList.Count() != 2) continue; 
    
                dictionaryToReturn.Add(attribList[0], attribList[1]);
            }
    
            return dictionaryToReturn;
        }
    }
    
    0 讨论(0)
  • 2021-01-28 02:34

    Read the documentation again, the second value is the length, not the index.

    As found on MSDN:

    public string Substring(
        int startIndex,
        int length
    )
    
    0 讨论(0)
提交回复
热议问题