Powershell脚本用于汇总字符串中的每个字符

Mat*_*att -1 string powershell parsing character

寻找一种方法来总结字符串中的所有唯一字符,所以如果字符串是:

!#*@&$&$&@^$*%(%&#
Run Code Online (Sandbox Code Playgroud)

该脚本将输出

1 ! found

2 # found

2 * found

2 @ found

4 & found

3 $ found

1 ^ found
Run Code Online (Sandbox Code Playgroud)

等等..

我找到了很多操纵字符串的方法,但不是这个.任何帮助都会统治!谢谢

Sha*_*evy 9

将字符串分成单独的字符并将它们分组:

PS> '!#@&$&$&@^$%(%&#'.ToCharArray() | Group-Object -NoElement | Sort-Object Count -Descending

Count Name
----- ----
    4 &
    3 $
    2 #
    2 @
    2 %
    1 !
    1 ^
    1 (
Run Code Online (Sandbox Code Playgroud)

如果将结果保存到变量,以后可以使用数组索引获取第一个项目(最常见的字符)(感谢@JNK).

PS>  $chars = '!#@&$&$&@^$%(%&#'.ToCharArray() | Group-Object ...   
PS>  $chars[0]

Count Name
----- ----
    4 &
Run Code Online (Sandbox Code Playgroud)