Home > Net >  Truncate, Convert String and set output as variable
Truncate, Convert String and set output as variable

Time:03-25

It seems so simple. I need a cmdlet to take a two word string, and truncate the first word to just the first character and truncate the second word to 11 characters, and eliminate the space between them. So "Arnold Schwarzenegger" would output to a variable as "ASchwarzeneg"

I literally have no code. My thinking was to

$vars=$var1.split(" ")
$var1=""
foreach $var in $vars{

????

}

I'm totally at a loss as to how to do this, and it seems so simple too. Any help would be appreciated.

CodePudding user response:

Here is one way to do it using the index operator [ ] in combination with the range operator ..:

$vars = 'Arnold Schwarzenegger', 'Short Name'
$names = foreach($var in $vars) {
    $i = $var.IndexOf(' ')   1 # index after the space
    $z = $i   10 # to slice from `$i` until `$i   10` (11 chars)
    $var[0]   [string]::new($var[$i..$z])
}
$names
  • Related