当我尝试将字符串限制为10个字符(长度不是10个或更多字符)时,substring会抱怨.我知道我可以测试长度,但我想知道是否有一个cmdlet可以满足我的需要.
PS C:\> "12345".substring(0,5)
12345
PS C:\> "12345".substring(0,10)
Exception calling "Substring" with "2" argument(s): "Index and length must refer to a location within the string.
Parameter name: length"
At line:1 char:18
+ "12345".substring( <<<< 0,10)
Run Code Online (Sandbox Code Playgroud)
Dmi*_*nov 23
你需要一个cmdlet吗?我想知道你为什么不喜欢长度.如果它是脚本的一部分,那么它看起来很好.
$s = "12345"
$s.substring(0, [System.Math]::Min(10, $s.Length))
Run Code Online (Sandbox Code Playgroud)
Ro *_* Mi 13
使用子字符串函数有它的局限性,并要求您首先捕获字符串的长度.当然,如果没有这个限制,你可以做到这一点.
以下将返回字符串的前5个字符
"1234567890"[0..4] -join "" # returns the string '12345'
Run Code Online (Sandbox Code Playgroud)
这将适用于比所需长度短的字符串
"1234567890"[0..1000] -join "" # returns the string '1234567890'
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
41490 次 |
最近记录: |