Monthly Archive

Categories

Get first non-repeating character in a string

How do you get first non-repeating character in a string.

 

In Windows PowerShell v5.1 you could use Group-Object but as I showed last time that approach has been taken away in PowerShell v6.1.

 

Instead you need to loop through the characters in the string and count them

function get-firstnonrepeatcharacter {
[CmdletBinding()]
param (
[string]$teststring
)

$a = [ordered]@{}

$teststring.ToLower().ToCharArray() |
foreach {
if ($a.$psitem) {
$a.$psitem += 1
}
else {
$a += @{$psitem = 1}
}

}

$a.GetEnumerator() | where Value -eq 1 | select -First 1

}

 

Input the test string through a parameter. Create an ORDERED hash table for the results – you need to preserve the order in which characters are counted!

 

Convert the string to lowercase (remove this step if your worried about case) and convert to an array of chars. Pipe into foreach-object. Test is the character is already in the hashtable. If it is increment the count. If it isn’t add it.

 

Use the getEnumerator() method to access the hash table. use where-object to filter for characters only appearing once. Select the first one.

 

$ts = 'lcoauywfnqumfheolfzaliigngulxqdbnzprnylfqvsxathrqsyjowm'

PS> get-firstnonrepeatcharacter -teststring $ts

Name Value
----      -----
c          1

Comments are closed.