Home > OS >  How can I replace a character of a item with a specific character in powershell?
How can I replace a character of a item with a specific character in powershell?

Time:04-29

I have the an array called $Map that has 29 strings of 23 characters. With the $CharY variable I specify the index of an item and with the $CharX variable I specify which character of that item should be replaced. How do I actually replace this character of the item with the character "0"? I tried using$Map[$CharY][CharX] but after running this command, an error is shown saying

At line:1 char:1
  $Map[$CharY][$CharX] = "0"
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      CategoryInfo          : InvalidOperation: (:) [], RuntimeException
      FullyQualifiedErrorId : CannotIndex

CodePudding user response:

.NET strings, which PowerShell uses, are immutable. You can read an individual character by index, but you can't modify it directly. Instead, create a new string with the modified character and assign it back to the array:

$Map = 1..29 | ForEach-Object { '1' * 23 }
$CharY = 1
$CharX = 2

$Line = $Map[$CharY].ToCharArray()
$Line[$CharX] = '0'
$Map[$CharY] = -join $Line

$Map

Output:

11111111111111111111111
11011111111111111111111
... [remaining lines omitted] ...

Explanations:

  • The first line fills $Map with 29 strings consisting of 23 characters each.
  • String.ToCharArray() is used to convert a string into a character array which can be modified.
  • The unary form of the -join operator is used to create a new string from the individual characters. Alternatively the String constructor that accepts a char array could be used: [String]::new($Line).
  • Related