In December I had fun solving the “riddles” at Advent Of Code and a large number of them (starting with number 1) had strings for input that needed to be parsed. So, posting this for myself, cause I can never remember it….
Convert a string to an array of single characters
1 2 3 4 5 6 7 8 9 10 |
# the input string $string = "This is a string" # convert it to a character array $array = $string.ToCharArray() # now we can iterate like any array foreach ($char in $array) { $char } |
The output:
Convert a string into an array of words
1 2 3 4 5 6 7 8 |
# the input string $string = "This is a string" # create an array from an arbitrary separator, in this case a space $array = $string.split(" ") # this will also work $array = $string -split " " |
Convert a string based on arbitrary characters
This also works with regular expressions…
1 2 3 4 5 6 7 |
$string = "a1b2c3d4e5f6" # split on numbers - remember, this will remove the numbers from the output $string -split "\d" # split on letters - this will remove the letters from the output $string -split "\D" |
$S.tochararray() should me $string.tochararray() in first example code.
Good catch, I’ve updated the post. Thank you for reading!
Andrew
Great post. This was very helpful. Thnx.
Thanks for this. I found it looking for help with string manipulation prepping for Advent of Code 2021.