Edit each Character in ToCharArray?
Solution 1:
If you want to cycle through a fixed number of items, use the remainder operator %
to "wrap around" and go back to zero:
$word = 'Rainbow'
$colors = -split 'Red Orange Yellow Green Blue Indigo Violet'
$htmlBuilder = [System.Text.StringBuilder]::new()
for($i = 0; $i -lt $word.Length; $i++)
{
# pick color, use % to wrap around at the end of the $colors array
$color = $colors[$i % $colors.Length]
# append html fragment
$htmlBuilder = $htmlBuilder.AppendFormat('<span style="color: {0}">{1}</span>', $color, $word[$i])
}
# output html string
$htmlBuilder.ToString()
Which produces:
<span style="color: Red">R</span><span style="color: Orange">a</span><span style="color: Yellow">i</span><span style="color: Green">n</span><span style="color: Blue">b</span><span style="color: Indigo">o</span><span style="color: Violet">w</span>
To show the color picker wrapping around and going back to red, here's the output with $word = 'StackOverflow'
:
<span style="color: Red">S</span><span style="color: Orange">t</span><span style="color: Yellow">a</span><span style="color: Green">c</span><span style="color: Blue">k</span><span style="color: Indigo">O</span><span style="color: Violet">v</span><span style="color: Red">e</span><span style="color: Orange">r</span><span style="color: Yellow">f</span><span style="color: Green">l</span><span style="color: Blue">o</span><span style="color: Indigo">w</span>
Solution 2:
Give this a try, there is no need for a for
loop in this case. You can use a foreach
loop (.foreach(..)
method in this case) to loop over each character and add your $x
and $y
tags on each element.
If you want all as single string instead of a multi-line string, use the .Append(..)
method instead of .AppendLine(..)
method of the StringBuilder.
Note, this assumes that $x
and $y
have the same number of elements.
$string = "Testers will test"
$x = '<tag1>', '<tag2>', '<tag3>', '<tag4>'
$y = '</tag1>', '</tag2>', '</tag3>', '</tag4>'
$i = 0
$builder = [System.Text.StringBuilder]::new()
$string.ToCharArray().ForEach({
process {
$null = $builder.AppendLine(('{0}{1}{2}' -f $x[$i], $_, $y[$i++]))
if($i -eq $x.Count) { $i = 0 }
}
end {
$builder.ToString()
}
})