Paxz
Paxz

Reputation: 3036

How to replace a single character in a string?

I'm trying to replace a character in a string after getting the string as input from the user super simple like this:

$thestring = Read-Host;

And now I want to change the 2nd character of the string. I don't care what letter the 2nd char is, but it needs to be set to 'a'.

I found the Replace() method to replace a chosen character:

$thestring = $string.Replace('b','a');

But it only goes for a given character. In C++ I would just say something like

thestring[1] = 'a';

And I'm trying to find something equal in PowerShell.

Upvotes: 2

Views: 4591

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200273

You can do the same in PowerShell if you cast the string to a character array:

[char[]]$char = $thestring
$char[1] = 'a'

Use the -join operator to convert the character array back to a string:

-join $char
$char -join ''

Other options are the Substring() method

$thestring.Substring(0,1) + 'a' + $thestring.Substring(2, $thestring.Length-2)

or regular expression replacements:

$thestring -replace '^(.).(.*)', '${1}a${2}'

Upvotes: 3

Related Questions