Convert a string to a character array

Hello everyone! We are back with a series of Brain Teasers. In the next 3 weeks we will publish one teaser per week.
It will run until Friday and the winner will be announced on the next Monday, taking home the eBook version of Microsoft Windows PowerShell 3.0 First Look written by Adam Driscoll. We would like to thank our sponsor Packt, one of the most prolific and fast-growing tech book publishers in the world, for providing such a cool prize.

OK, time to start your engine, here goes the first one 🙂

You have a string, “PowerShell”, you need to break it to its individual characters so the result is a collection of System.Char objects:

P
o
w
e
r
S
h
e
l
l

Requirements

1. You cannot cast the string to char array, e.g [char[]]”PowerShell”
2. You cannot use the String.ToCharArray method

The most shortest/elegant solution wins.

Good luck!

About the author: Shay Levy

Shay Levy is a Co-founder and editor of the PowerShell Magazine. He is a multiple-year recipient of the Microsoft MVP award, and a Microsoft Certified Trainer (MCT). Shay often covers PowerShell related topics on his blog and you can also follow him on Twitter at @ShayLevy

Related Posts

30 Comments

      1. That is right, the split op returns strings. To get an array of Chars
        from a String of any length you can do this:

        ($s=’PowerShell’)[0..$s.Length]

    1. I think this one is best as it will take any string. Thetwo above it are great however if the string length changes it will break.

  1. “PowerShell” -split ‘(?<=.)(?=.)'

    sorry if this is a repost. Somehow, my post vanished… 🙂

    1. Best one i see after reading others answers is:

      “Powershell”[0..”Powershell”.Length]

      or
      $str[0..$str.length]

  2. “PowerShell”|%{for ($i=0;$i -lt $_.Length; ++$i) { $_[$i] }}

    or alternatively

    “PowerShell”|%{$s=$_;(0..($s.Length))|%{$s[$_]}}

    1. Wow, and after reading this is the same as doing
      “PowerShell”[0..”PowerShell”.Length]

      Awesome!

Comments are closed.

%d bloggers like this: