Powershell replace character in string at position

Powershell: Replacing a Character in a String at a Specific Position

In Powershell, you can replace a character in a string at a specific position using string manipulation functions and the concept of string indexing. Here’s an example:

$originalString = "Hello, World!"
$index = 7
$replacementChar = "?"

$newString = $originalString.Substring(0, $index) + $replacementChar + $originalString.Substring($index + 1)

# Output the updated string
$newString

In this example, we have an original string “Hello, World!” that we want to modify. We specify the position of the character we want to replace using the variable $index (7). In this case, we want to replace the comma (,) at index 7.

We then define the replacement character using the variable $replacementChar ("?"). You can replace it with any character or string you desire.

To replace the character, we use the .Substring() method of the original string. We first retrieve the substring from the start of the string up to the index using $originalString.Substring(0, $index). Then, we concatenate it with the replacement character and the substring of the original string starting from the index after the character we want to replace using $originalString.Substring($index + 1).

The resulting updated string is stored in the variable $newString. You can now use or further manipulate this modified string as needed.

Running the code will output the updated string:

Hello? World!

As you can see, the comma character at position 7 has been replaced with the question mark.

Leave a comment