CHAR and STRING classes - how to be consistent

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.

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 :wink:

Why use a character array?

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:


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

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

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.

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

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