modifying an element in an element

Welcome Forums General PowerShell Q&A modifying an element in an element

This topic contains 6 replies, has 3 voices, and was last updated by

 
Participant
3 years, 4 months ago.

  • Author
    Posts
  • #27835

    Participant
    Points: 28
    Rank: Member

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

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

    Keymaster
    Points: 1,704
    Helping HandTeam Member
    Rank: Community Hero

    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

    Member
    Points: 0
    Rank: Member

    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

    Participant
    Points: 28
    Rank: Member

    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

    Member
    Points: 0
    Rank: Member

    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

    Participant
    Points: 28
    Rank: Member

    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

    Participant
    Points: 28
    Rank: Member

    Thanks for your example on how to do it 🙂

The topic ‘modifying an element in an element’ is closed to new replies.