$string.Substring 索引/长度异常 [英] $string.Substring Index/Length exception

查看:93
本文介绍了$string.Substring 索引/长度异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 Substring 时遇到此异常:

I'm getting this exception when using 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 I'm getting given the index and length are correct.

我正在做以下事情:

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

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

Even attempting to hard code it throws the same exception:

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

有什么我遗漏的吗?

推荐答案

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

Your first argument is that starting position in the string, and the second is the length of the substring, starting at that position. The expression for the 2 characters at positions 68 and 69 would be:

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

这篇关于$string.Substring 索引/长度异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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