$ string.Substring Index / exception length

I get this exception when using a substring:

Exception calling "Substring" with "2" argument(s): "Index and length must
refer to a location within the string.
Parameter name: length"
At line:14 char:5
+     $parameter = $string.Substring($string.Length-1, $string ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ArgumentOutOfRangeException

I understand its meaning, but I'm not sure why they give me a pointer and the length is correct.

I do the following:

$string = "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\hid\Parameters\0"
$parameter = $string.Substring($string.Length-1, $string.Length)

Even trying hard code makes the same exception:

$parameter = $string.Substring(68, 69)

Is there something I am missing?

+4
source share
3 answers

Your first argument is that the starting position is in the string, and the second is the length of the substring starting at that position. Expression for two characters at positions 68 and 69:

$parameter = $string.Substring(68,2)
+3
source

What the error message is trying to tell you: the beginning of the substring plus the length of the substring (second parameter) must be less than or equal to the length of the string. The second parameter is not the final position of the substring.

:

'foobar'.Substring(4, 5)

5, 5- ( 0, , 4 5- ):

foobar
    ^^^^^  <- substring of length 5

, 3-5 .

:

$str   = 'foobar'
$start = 4
$len   = 5
$str.Substring($start, [Math]::Min(($str.Length - $start), $len))

, , , :

$str = 'foobar'
$str.Substring(4)
+4

If the last character of the string is all you need, you can achieve this by simply treating the string as an array of characters and using the appropriate index notation:

'HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\hid\Parameters\0'[-1]
+3
source

Source: https://habr.com/ru/post/1609519/


All Articles