2017-07-25 56 views
4

我試圖在Kotlin中填充字符串以在控制檯輸出上實現一些正確的對齊。沿着這些路線的東西:Kotlin中的填充字符串

accountsLoopQuery        - "$.contactPoints.contactPoints[?(@.contactAccount.id)]" 
brokerPassword        - ***** 
brokerURI          - tcp://localhost:61616 
brokerUsername        - admin 
contactPointPriorityProperties    - "contactPointPriority.properties" 
customerCollection       - "customer" 
customerHistoryCollection      - "customer_history" 
defaultSystemOwner       - "TUIGROUP" 

我已經結束了編碼這種方式 - 與Java的的String.format作弊:

mutableList.forEach { cp -> 
    println(String.format("%-45s - %s", cp.name, cp.value)) 
} 

是否存在與科特林庫這樣做一個適當的方式?

回答

7

您可以從kotlin-stdlib爲使用.padEnd(length, padChar = ' ') extension。它接受所需length和可選padChar(默認爲空白):

mutableList.forEach { 
    println("${it.name.padEnd(45)} - ${it.value}") 
} 

還有padStart即對準在另一個方向上的填充。

+0

很好的答案。我已經嘗試過你的建議,它的作用就像一個魅力。 –

4

可以使用String#format擴展功能,而不是,事實上,它是內聯調用點函數與java.lang.String#format例如:

mutableList.forEach { cp -> 
    println("%-45s - %s".format(cp.name, cp.value)) 
} 
+0

是的,這很好。 –

+0

@ gil.fernandes完全沒有。很高興它幫助你。 –