[英]Powershell: Find number of occurrences of a specific numeric value from an integer array
我有一個 integer 數組,如下所示,我想在 powershell 中計算該數組中 1 的數量,有人可以幫我嗎?
[array]$inputs = 81,11,101,1811,1981
$count = 0
foreach($input in $inputs)
{
Write-Host "Processing element $input"
$count += ($input -like "*1*" | Measure-Object).Count
}
Write-Host "Number of 1's in the given array is $count"
它在該數組中只給了我 5 個 1,但預期的答案是 10。任何幫助將不勝感激
從旁注開始:
不要將
$Input
用作自定義變量,因為它是保留的自動變量
對於您正在嘗試的內容:
您遍歷一個數組並檢查每個項目(將自動類型轉換為字符串)是否-like
一個1
前面有任意數量的字符,然后是任意數量的字符,無論是真還是假(而不是總數字符串中的一個)。
反而
您可能希望將Select-String
cmdlet 與-AllMatches
開關一起使用,該開關會計算所有匹配項:
[array]$inputs = 81,11,101,1811,1981
$count = 0
foreach($i in $inputs)
{
Write-Host "Processing element $input"
$count += ($i | Select-String 1 -AllMatches).Matches.Count
}
Write-Host "Number of 1's in the given array is $count"
事實上,由於 PowerShell成員枚舉功能,您甚至不必為此遍歷每個數組項,只需將其簡化為:
[array]$inputs = 81,11,101,1811,1981
$count = ($Inputs | Select-String 1 -AllMatches).Matches.Count
Write-Host "Number of 1's in the given array is $count"
Number of 1's in the given array is 10
我用下面的腳本解決了上述問題,
[string]$inputs = 81,11,101,1811,1981
$count = 0
foreach($i in $inputs.ToCharArray())
{
if($i -eq "1")
{$count++}
}
Write-Host "Number of 1's in the given array is $count"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.