.NET字符串Split() [英] .NET String Split()

查看:135
本文介绍了.NET字符串Split()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PowerShell -split 运算符和.NET Split()方法的作用似乎完全不同。



.NET将分隔符字符串视为字符数组。

  $ str = 123456789 
写主机 .NET Split():
$ lines = $ str.Split( 46)
写主机计数:$($ lines .Length)
$ lines

$ str = 123456789
Write-Host -split运算符:
$ lines = $ str -split 46
Write-Host计数:$($ lines.Length)
$ lines

输出:

  .NET Split():
计数:3
123
5
789


-拆分运算符:
计数:1
123456789

是否有一种方法可以使.NET应用程序使用与PowerShell相同的技术,并将字符串分隔符用作一个固定单元?希望没有RegEx。



这在PowerShell中可以使用Split():

 写入主机除以46: 
123456789 .Split([string []] 46,[StringSplitOptions] :: None)

写入主机`n`n除以45:
123456789 .Split([string []] 45,[StringSplitOptions] :: None)


46:
123456789


除以45:
123
6789


解决方案

.NET的String.Split方法具有两个(一组)重载。第一个接收字符数组,第二个接收字符串数组。实际上并没有接收字符串的重载。第一个字符的行为与您描述的相同,每个字符被单独拆分。第二个命令按照整个字符串进行拆分,就像您希望的那样。



由于PowerShell解析参数的方式,传递给Split的字符串将被解析为char数组,并且第一个重载被调用。如果您可以明确指定 46是一个仅包含一个字符串的数组,则它应会为您提供所需的行为。


It seems that the PowerShell -split operator and .NET Split() method act completely different.

.NET treats separator strings as if they were character arrays.

$str = "123456789"
Write-Host ".NET Split(): "
$lines = $str.Split("46")
Write-Host "Count: $($lines.Length)"
$lines

$str = "123456789"
Write-Host "-split operator: "
$lines = $str -split "46"
Write-Host "Count: $($lines.Length)"
$lines

Output:

.NET Split():
Count: 3
123
5
789


-split operator:
Count: 1
123456789

Is there a way to make a .NET application use the same technique as the PowerShell, and use the string separator as one solid unit? Hopefully, without RegEx.

This worked in PowerShell, using the Split():

Write-Host "Divided by 46:"
"123456789".Split([string[]]  "46", [StringSplitOptions]::None)

Write-Host "`n`nDivided by 45:"
"123456789".Split([string[]]  "45", [StringSplitOptions]::None)


Divided by 46:
123456789


Divided by 45:
123
6789

解决方案

.NET's String.Split method has two (groups of) overloads. The first receives a character array, and the second a string array. There isn't actually an overload that receives a string. The first one behaves like you describe, with each character being split individually. The second splits along whole strings, like you want it to.

Due to the way PowerShell parses the parameters, a string passed to Split will be parsed as a char array, and the first overload called. If you could explicitly specify that the "46" is an array containing just one string, it should give you the behavior you want.

这篇关于.NET字符串Split()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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