gpt4 book ai didi

Powershell 排序命令未按预期工作

转载 作者:行者123 更新时间:2023-12-02 23:07:14 24 4
gpt4 key购买 nike

我使用这组命令来检查键盘字符上的排序命令。

$symb="a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","²","1","2","3","4","5","6","7","8","9","0","°","+","&","é",'"',"'","(","-","è",[regex]::escape('`'),"_","ç","à",")","=","~","#","{","[","|","\","^","@","]","}","$","¨","ˆ","£","¤","ù","*","%","µ","<",",",";",":","!",">","?",".","/","§","€"; $symb|sort|ac file.txt;(gc file.txt)-join""

这是我在文件和控制台中得到的内容。

'-!"#$%&()*,./:;?@[\]ˆ^_`{|}~¨£¤€+<=>§°µ012²3456789aAàbBcCçDdEeéèfFgGhHIiJjKkLlmMNnOoPpqQRrsStTuUùvVwWXxyYzZ

在大约一半的小写和大写字母对的情况下,顺序是相反的;似乎它应该总是“小写在前,大写在后”。如何解决这个问题?

最佳答案

PowerShell - 与 .NET 框架的类型不同 - 默认情况下不区分大小写;如果您想要区分大小写的行为,则需要选择加入

Sort-Object为例您需要使用其 -CaseSensitive 开关:

PS> -join ('a', 'B', 'A', 'b' | Sort-Object -CaseSensitive)
aAbB

正如您所料,这会导致小写字母首先排序,因为在(美国英语)排序顺序中,小写字母的排序权重低于大写字母 - 即使尽管就其 Unicode 代码点而言,关系是相反的(例如,[int] [char] 'a'97,而 [int] [char]'A'65)。

(如果数组包含 [char] 实例,则将应用基于代码点的排序,但 PowerShell 没有 [char] 文字,因此文字如 'a' 是长度为 1[string];但是,您可以使用显式强制转换: -join ([char] 'A', [char] 'a' | Sort-Object -CaseSensitive) 产生 'Aa',即排序大写 首先。)


如果没有 -CaseSensitive,给定字母的小写和大写变体具有相同的排序权重,因此不能保证它们之间的特定顺序。

例如,以下循环会快速退出:

$prevResult = $null
while ($true) {

# Get a shuffled array of lower- and uppercase letters.
$arr = 'a', 'B', 'A', 'b'
$arr = $arr | Get-Random -Count $arr.Count

# Sort it case-INsensitively.
$result = -join ($arr | Sort-Object)

$result # output

# See if the result is different from the previous one.
# Note the use of -cne rather than just -ne:
# -ce is the case-*sensitive* variant of -ne
if ($prevResult -and $prevResult -cne $result) {
Write-Warning "Output order has changed."
break
}
$prevResult = $result

}

但是,请注意,Sort-Object 似乎执行稳定排序:也就是说,对于给定的输入数组,结果数组始终相同。也就是说,如果将 $arr 的创建移到 while 循环之外,结果始终相同,并且循环永远不会退出。

关于Powershell 排序命令未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59741843/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com