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

Advertisements
This entry was posted in Powershell. Bookmark the permalink.

1 Response to Get first non-repeating character in a string

  1. is there a benefit of using if-else instead of straightforwardly incrementing it?
    $teststring.ToLower().ToCharArray() | foreach { $a.$psitem += 1 }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s