modifying an element in an element

how could I change the letter ‘k’ to a letter ‘m’ in the following array?

$myarray = ( 'aaa', 'bbb', 'dkd', 'bbb')

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?

The -replace operator works on arrays just as well as single values. For example:

$myarray = ( 'aaa', 'bbb', 'dkd', 'bbb')

$myarray = $myarray -replace 'k', 'm'

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.

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)

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[5] = "h"

Thanks for your example on how to do it :slight_smile: