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:



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!

Filed in: Brainteasers Tags: ,

30 Responses to "Convert a string to a character array"

  1. John Ludlow says:

    $s = “Powershell”; for ($i = 0; $i -lt $s.length; $i++) { $s[$i] }

  2. _Emin_ says:

    “PowerShell” -split”(?<=G.{1})"

  3. Matt says:


  4. Crow says:


    • BacktoPoSh says:

      Correct me if I’m wrong, but this outputs String objects, not Char objects

      • Crow T says:

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


  5. Crow T says:


  6. kevin says:

    For any string $test:


  7. kevin says:

    Actually, you don’t need the parenthesis:


  8. ‘PowerShell’.GetEnumerator() 😉

    • Johnny Leuthard says:

      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.

    • Crow T says:

      In your case GetEnumerator returns a CharEnumerator, not a Char[]

  9. Mike F Robbins says:

    ([regex]::Matches(“PowerShell”,’.’,’RightToLeft’) | % {$_}) -join ” + “`n”

  10. Tobias Weltner says:

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

  11. Tobias Weltner says:

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

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

  12. Larry says:


  13. Crow T says:


  14. sahal says:

    “Powershell” -split “”

  15. “PowerShell”.GetEnumerator()

  16. Peter says:

    “Powershell” -split “B” | foreach {[char[]]$arr += $_}

  17. Nat Davis says:

    I love regex, how about this


  18. [System.Linq.Enumerable]::ToArray(“PowerShell”)

  19. Chris Bennett says:

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

    or alternatively


    • Chris Bennett says:

      Wow, and after reading this is the same as doing


  20. proftech says:

    Nice scripts… great contributors…

© 2018 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: