我有幾個由這樣的字串組成的串列(把它們想象成一棵排序樹):
$list1:
data-pool
data-pool.house 1
data-pool.house 1.door2
data-pool.house 1.door3
data-pool.house2
data-pool.house2.door 1
為了使它們更容易決議為樹,如何根據.出現的字符數量縮進它們,同時丟棄行中較早的重復文本?例如:
data-pool
house 1
door2
door3
house2
door 1
我處理它的方法是計算.s的出現次數,.split('.').Length-1以確定所需縮進的數量,然后使用空格添加空格.IndexOf('.'),.Substring(0, <position>)感覺過于復雜 - 或者我就是無法理解如何以一種不太復雜的方式來完成它。
uj5u.com熱心網友回復:
我認為只要從一行到n另一行的節點數是有序的,這應該有效,我的意思是,如果例如當前節點有元素而下一個節點有n 2或更多元素,它看起來不會“漂亮” 。
為了正確看待它,使用這個串列作為例子:
$list = @'
data-pool
data-pool.house 1
data-pool.house 1.door2
data-pool.house 1.door3
data-pool.house 1.door4.something1
data-pool.house2
data-pool.house2.door 1
data-pool.house2.door 2.something1
data-pool.house2.door 3.something1.something2
data-pool.house3
data-pool.house3.door 1
data-pool.house3.door 2
'@ -split '\r?\n'
該函式indent將獲取串列的每一行并使用.分隔符將其拆分,如果拆分后的元素數小于或等于1它,則不會執行任何修改并按原樣顯示該行,否則,它將乘以$IndentType包含2 個空格乘以拆分陣列的元素數減 1,并將其與拆分陣列的最后一個元素連接。
function indent {
param(
[string]$Value,
[string]$IndentType = ' '
)
$out = $Value -split '\.'
$level = $out.Count - 1
'{0}{1}' -f ($null,($IndentType*$level))[[int]($out.Count -gt 1)], $out[-1]
}
$list.ForEach({ indent $_ })
樣本:
data-pool
house 1
door2
door3
something1
house2
door 1
something1
something2
house3
door 1
door 2
uj5u.com熱心網友回復:
獲取字串最后一個元素的方法如下
## String
$string = "data-pool.house 1"
## split the string into an array every "."
$split = $string.split(".")
## return the last element of the array
write-host $split[-1] -ForegroundColor Green
然后針對每個字串進行測驗
$myArray = ("data-pool", "data-pool.house 1", "data-pool.house 1.door2", "data-pool.house 1.door3", "data-pool.house2", "data-pool.house2.door 1")
ForEach($Name in $myArray) {
## String
$Name = $Name.ToString()
$string = $Name
$split = $string.split(".")
## return the last element of the array
write-host $split[-1] -ForegroundColor Green
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/372248.html
標籤:电源外壳
