我想快速在同一行上左右对齐文本。例如,我有一个字符串,其产品名称在左侧,价格在右侧。两者在同一条线上。这可能吗?
在蓝牙打印中,每行正好有32个字符。我需要这样做。
答案 0 :(得分:2)
如果我理解正确,那么您需要这样的东西:
func alignLeftAndRight(left: String, right: String, length: Int) -> String {
// calculate how many spaces are needed
let numberOfSpacesToAdd = length - left.count - right.count
// create those spaces
let spaces = Array(repeating: " ", count: numberOfSpacesToAdd < 0 ? 0 : numberOfSpacesToAdd).joined()
// join these three things together
return left + spaces + right
}
用法:
print(alignLeftAndRight(left: "Product", right: "Price", length: 32))
print(alignLeftAndRight(left: "Foo", right: "1", length: 32))
print(alignLeftAndRight(left: "Product", right: "123", length: 32))
print(alignLeftAndRight(left: "Something", right: "44", length: 32))
print(alignLeftAndRight(left: "Hello", right: "7777", length: 32))
输出:
Product Price
Foo 1
Product 123
Something 44
Hello 7777