問題描述
在 Powershell 中拆分和添加字符串 (Splitting and Adding String in Powershell)
我有以下問題:
我有一個字符串,比如 $word ='ABC.DEF.GHI'
我想拆分這個在點處將字符串插入數組並添加一個字符串。期望的結果如下:
$arrayWordSplitted = 'ABC 123; DEF 123; GHI 123'
with $arrayWordSplitted[0] = 'ABC 123'
我嘗試了 .split()‑ 方法,但我不能用這個添加每個元素。
我試過這樣的:$wordSplitted = $word.split('.') + '123'
但我得到 $wordSplitted='ABC; 防禦;全球健康指數;123
powershell中如何對所有元素進行拆分和添加?
參考解法
方法 1:
I guess you're looking for that :
$wordSplitted=$word.split('.') | %{ $_ += ' 123' ; $_ }
Some details: $word.split('.')
produces a string array with words, string array that we pass through a pipe (|
) to an elements iterator ( %{ }
). In this iterator, we add to the string element ($_
) the string ' 123'
and then send it back as an output with ; $_
. Thus, PowerShell build an array of strings with all strings suffixed with ' 123'
and stores it in $wordSplitted
.
EDIT: You can reduce it like @Olaf has done it with :
$wordSplitted=$word.split('.') | %{ $_ + ' 123' }
方法 2:
A little more verbose version would be something like this:
$word = 'ABC.DEF.GHI'
$SplittedWord = $word ‑split '\.'
$AddedStrings = $SplittedWord | ForEach‑Object {$_ + ' 123'}
If you want to re‑join them ...
$arrayWordSplitted = $AddedStrings ‑join '; '
And the output would be:
ABC 123; DEF 123; GHI 123
(by TheCodingKing、Zilog80、Olaf)