Reputation: 4815
I am working on a script in which I have to read alternating characters from a string.
I am using the following approach:
$s = "abcdef"
$chars = $s.ToCharArray()
For( $i = 0; $i -lt $chars.Count; $i = $i + 2){
$chars[$i]
}
Is there a simpler approach, especially one based on a pipeline?
Upvotes: 2
Views: 491
Reputation: 68301
Another possibility:
$string = 'abcdefg'
$i=0
([char[]]$string).where({$i++ %2})
b
d
f
Upvotes: 3
Reputation: 58981
You could use a simple regex (demo) to match two characters and replace it with the first one:
$s -replace '(.).', '$1'
Output:
ace
If you want to have characters, just cast it to an char[]
:
[char[]] ($s -replace '(.).', '$1')
or split the string (thanks PetSerAl):
$s -replace '(.).', '$1' -split '(?!^|$)'
Upvotes: 5
Reputation: 46710
Love the regex answer but wanted to include something that used the pipeline more and Select-Object
$string = "abcdef"
[char[]]$string | Select-Object -Index (0..($string.Length-1) | Where-Object{$_ % 2})
-Index
takes the length of the string and returns and array of odd numbers used to extract the characters from the char array. Using !($_ % 2)
would alternate the returned set. In both cases I am taking advantage of the value returned by the modulus operator. If the number is even in the above example 0 is returned which evaluates to false. $_ % 2 -eq $false
would accomplish the same thing and be more readable depending.
Upvotes: 3
Reputation: 13483
Not sure if it's simpler, but it's different:
$s = "abcdef"
for ($i = 0; $i -lt $s.Length; $i++)
{
if ($i % 2 -ne 0)
{
$s[$i]
}
}
Upvotes: 2