Search code examples
stringpowershellfor-loopinsert

How do I insert chars at multiple places in a string?


I want to insert ":" after every second character - the end result should look like this 51:40:2e:c0:11:0b:3e:3c.

My solution

$s = "51402ec0110b3e3c"

for ($i = 2; $i -lt $s.Length; $i+=3)
{
$s.Insert($i,':')
}

Write-Host $s

returns

51:402ec0110b3e3c
51402:ec0110b3e3c
51402ec0:110b3e3c
51402ec0110:b3e3c
51402ec0110b3e:3c
51402ec0110b3e3c

Why is $s being returned multiple times when I only put Write-Host at the very end? Also, it looks like $s keeps returning to its original value after every loop, overwriting the previous loops...

I would've thought that the loop accomplishes the same as this:

$s = $sInsert(2,':').Insert(5,':').Insert(8,':').Insert(11,':').Insert(14,':').Insert(17,':').Insert(20,':')

Solution

  • This is because insert returns a new string. It does not modify the string in place. So, you have to change

    $s.Insert($i,':')
    

    to

    $s = $s.Insert($i,':')