modifying an element in an element

This topic contains 6 replies, has 3 voices, and was last updated by  Shane Lindberg 2 years, 2 months ago.

  • Author
    Posts
  • #27835

    Shane Lindberg
    Participant

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

    $myarray = ( 'aaa', 'bbb', 'dkd', 'bbb')
  • #27837

    Don Jones
    Keymaster

    It might help if you could share the larger question as opposed to a somewhat disconnected example.

    $myarray[2].replace('k','m')

    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?

  • #27838

    Dave Wyatt
    Moderator

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

    $myarray = ( 'aaa', 'bbb', 'dkd', 'bbb')
    
    $myarray = $myarray -replace 'k', 'm'
    
  • #27839

    Shane Lindberg
    Participant

    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.

  • #27840

    Dave Wyatt
    Moderator

    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)
    
  • #27871

    Shane Lindberg
    Participant

    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"
  • #27873

    Shane Lindberg
    Participant

    Thanks for your example on how to do it 🙂

You must be logged in to reply to this topic.