Author Posts

July 23, 2018 at 2:55 am

My dilemma looks extremely simple but I can't quite get it right.
I have an array of characters which was the result of typed input:

     $f = $Input.ToCharArray()

I get an error message from Powershell when I subsequently run the statements

     $ch = $f[]
     $x = $ch.Contains() 

complaining that the System.Char class does not have the Contains method, which is true.
It's obvious there is a distinction between CHAR and STRING classes ???
How do I "get around" this? Would be grateful for any appropriate solution, advice or tip.

July 23, 2018 at 5:54 am

It might not be the cause of your problem but I think you should not be using $input as a variable name as it is a reserved automatic variable of Powershell Get-Help about_Automatic-Variables.

A string is a collection of chars and a char is a single char. If you like to chaeck if a single char is in your $input just do

$input.Contains("charachter to check for")

... and of course with another variable name 😉

July 23, 2018 at 12:16 pm

Why use a character array?

July 23, 2018 at 3:22 pm

Your second snippet is taking one character out of the array and asking if the one character contains some other character; that doesn't make any sense.

Are you just trying to see if a character is in a string? Then just do:

$string.Contains($Char)

Are you trying to check if a character is in a char array? Do:

$CharArray = $String.ToCharArray()
$CharArray -contains $Char

July 24, 2018 at 2:27 am

You hit on the crux of the issue: I reversed / confused the check of whether a single character
was one of several characters in the "valid list",i.e., I meant to have

    $ValidList = '0123456789'
    $singlechar = ...  # ---- 
    $a = $ValidList.Contains($singlechar)
    If ($a -EQ $True) { # $singlechar is valid numeric char ... }

But instead, I wrote the opposite: reversing $ValidList with $singlechar, which as you pointed out, makes no sense.
Many thanks Mr Sallow for taking the time to help me realize where I went wrong.
Best,

July 24, 2018 at 5:54 am

You could even save one more line of code with this:

if ($ValidList.Contains($singlechar)) { # $singlechar is valid numeric char ... }