July 23, 2015 at 7:34 pm #27835
how could I change the letter 'k' to a letter 'm' in the following array?
$myarray = ( 'aaa', 'bbb', 'dkd', 'bbb')
July 23, 2015 at 7:44 pm #27837
It might help if you could share the larger question as opposed to a somewhat disconnected example.
Would produce the modified element, for example. But I'm not sure if you're looking for some array enumerator, or some array based regex capability, or something else. Are you looking for the ability to refer to specific characters within a string by number? Or how to refer to array elements?
July 23, 2015 at 7:49 pm #27838
The -replace operator works on arrays just as well as single values. For example:
$myarray = ( 'aaa', 'bbb', 'dkd', 'bbb') $myarray = $myarray -replace 'k', 'm'
July 23, 2015 at 8:16 pm #27839
I am trying to make a tic tac toe game. I have an ascii tic tac toe board of 19 rows, where each row is an element in the array. As a player chooses a spot, I need to modify the array to add an ascii "x" or "o" to the board.
July 23, 2015 at 8:30 pm #27840
Ah, you wouldn't want the -replace operator then, as that would change everything, everywhere. Working with an array of strings here is a little bit awkward, as you can't change a string. (You have to build a new one and then assign it back into the array.) A two-dimensional array of strings or characters is easier to modify, but then you will need to write a quick function to display it in rows. Either approach is probably fine.
Here's one way you could do this, if you kept it as an array of strings:
$myarray = ( 'aaa', 'bbb', 'dkd', 'bbb') $rowIndexToChange = 2 $colIndextoChange = 1 $chars = $myarray[$rowIndexToChange].ToCharArray() $chars[$colIndextoChange] = 'm' $myarray[$rowIndexToChange] = New-Object string($chars, 0, $chars.Count)
July 24, 2015 at 2:52 pm #27871
I see my main root problem. I did not realize strings were not mutable(or I forgot). I was trying to change them like this, but of coarse got an error.
In the following example I was trying to change the 6th element of the string to "h". I do now realize I need to reassign the whole string. Thanks!
$mystring = "h"
July 24, 2015 at 5:25 pm #27873
Thanks for your example on how to do it 🙂
You must be logged in to reply to this topic.