$string.Substring 索引/长度异常

sta*_*mps 6 powershell

使用 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
Run Code Online (Sandbox Code Playgroud)

我理解它的意思,但我不确定为什么我得到的索引和长度是正确的。

我正在做以下事情:

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

即使尝试硬编码它也会抛出相同的异常:

$parameter = $string.Substring(68, 69)
Run Code Online (Sandbox Code Playgroud)

有什么我想念的吗?

mjo*_*nor 6

您的第一个参数是字符串中的起始位置,第二个参数是从该位置开始的子字符串的长度。位置 68 和 69 处的 2 个字符的表达式为:

$parameter = $string.Substring(68,2)
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!那个有效。最终执行`$parameter = $string.Substring($string.Length-1, 1)` 来获取我需要的最后一个字符。 (2认同)

Ans*_*ers 5

错误消息试图告诉您的是:子字符串的开头加上子字符串的长度(第二个参数)必须小于或等于字符串的长度。第二个参数不是子串的结束位置。

例子:

'foobar'.Substring(4, 5)
Run Code Online (Sandbox Code Playgroud)

这将尝试从第 5 个字符开始提取长度为 5 的子字符串(索引从 0 开始,因此第 5 个字符的索引为 4):

'foobar'.Substring(4, 5)
Run Code Online (Sandbox Code Playgroud)

这意味着子字符串的第 3-5 个字符将在源字符串之外。

必须将子字符串语句的长度限制为长度减去子字符串的起始位置:

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

或者,如果您只想从给定位置开始字符串的尾端,则可以完全省略长度:

$str = 'foobar'
$str.Substring(4)
Run Code Online (Sandbox Code Playgroud)