我正在尝试打印所有填充到相同宽度的字符串列表。
在C中,我会使用printf("%40s", cstr),
之类的东西,其中cstr是一个C字符串。
在斯威夫特,我能提出的最好的是:
line += String(format: "%40s",string.cStringUsingEncoding(<someEncoding>))
有更好的方法吗?
答案 0 :(得分:58)
在 Swift 3 中,您可以使用:
let str = "Test string"
let paddedStr = str.padding(toLength: 20, withPad: " ", startingAt: 0)
结果字符串:"Test string "
如果您需要向左侧填充文本(右对齐),您可以将以下函数编写为String
的扩展名:
extension String {
func leftPadding(toLength: Int, withPad character: Character) -> String {
let newLength = self.characters.count
if newLength < toLength {
return String(repeatElement(character, count: toLength - newLength)) + self
} else {
return self.substring(from: index(self.startIndex, offsetBy: newLength - toLength))
}
}
}
所以如果你写:
let str = "Test string"
let paddedStr = str.leftPadding(toLength: 20, withPad: " ")
结果字符串:" Test string"
在 Swift 4.1 中,不推荐使用substring
方法,并且有许多新方法可以获取子字符串。 prefix
,suffix
或使用String
订阅Range<String.Index>
。
对于之前的扩展,我们可以使用suffix
方法来完成相同的结果。由于suffix
方法返回String.SubSequence
,因此需要在返回之前将其转换为String
。
extension String {
func leftPadding(toLength: Int, withPad character: Character) -> String {
let stringLength = self.count
if stringLength < toLength {
return String(repeatElement(character, count: toLength - stringLength)) + self
} else {
return String(self.suffix(toLength))
}
}
}
答案 1 :(得分:17)
NSString
使用stringByPaddingToLength:
方法:
line += string.stringByPaddingToLength(40, withString: " ", startingAtIndex: 0)
答案 2 :(得分:6)
将所有字符串格式代码放入extension
并在任何地方重复使用。
extension String {
func padding(length: Int) -> String {
return self.stringByPaddingToLength(length, withString: " ", startingAtIndex: 0)
}
func padding(length: Int, paddingString: String) -> String {
return self.stringByPaddingToLength(length, withString: paddingString, startingAtIndex: 0)
}
}
var str = "str"
print(str.padding(10)) // "str "
print(str.padding(10, paddingString: "+")) // "str+++++++"
答案 3 :(得分:4)
<a href="/about#about-us-content">Skip to About Us Content</a>
<div id="about-us-content">Insert stuff</div>
extension RangeReplaceableCollection where Self: StringProtocol {
func paddingToLeft(upTo length: Int, using element: Element = " ") -> SubSequence {
return repeatElement(element, count: Swift.max(0, length-count)) + suffix(Swift.max(count, count-length))
}
}
答案 4 :(得分:2)
以下两个函数返回填充为给定宽度(左对齐或右对齐)的字符串。它是纯Swift 4,没有NSString,也没有C字符串。您可以选择是否将长度超过填充宽度的字符串截断。
extension String {
func rightJustified(width: Int, truncate: Bool = false) -> String {
guard width > count else {
return truncate ? String(suffix(width)) : self
}
return String(repeating: " ", count: width - count) + self
}
func leftJustified(width: Int, truncate: Bool = false) -> String {
guard width > count else {
return truncate ? String(prefix(width)) : self
}
return self + String(repeating: " ", count: width - count)
}
}
答案 5 :(得分:0)
这是我针对String
的解决方案,但我敢肯定有人比我聪明,可以使其变得更通用。
extension String {
func frontPadding(toLength length: Int, withPad pad: String, startingAt index: Int) -> String {
return String(String(self.reversed()).padding(toLength: length, withPad: pad, startingAt: index).reversed())
}
}
答案 6 :(得分:0)
import Foundation // for NSString.padding()
/**
* Custom Extension's API
* ------------------------------
* • str.padEnd(_:_:)
* • str.padStart(_:_:)
* ------------------------------
* • int.padStart(_:_:forceSign:)
*/
extension String {
// str.padEnd(8, "-")
func padEnd(_ length: Int, _ pad: String) -> String {
return padding(toLength: length, withPad: pad, startingAt: 0)
}
// str.padStart(8, "*")
func padStart(_ length: Int, _ pad: String) -> String {
let str = String(self.reversed())
return String(str.padEnd(length, pad).reversed())
}
}
extension Int {
// int.padStart(8)
func padStart(
_ length: Int, // total length
_ pad: String = "0", // pad character
forceSign: Bool = false // force + sign if positive
) -> String {
let isNegative = self < 0
let n = abs(self)
let str = String(n).padStart(length, pad)
return
isNegative ? "- " + str :
forceSign ? "+ " + str :
str
}
}
// test run
let s1 = "abc"
[
s1.padEnd(15, "*"), // abc************
s1.padStart(15, "*"), // ************abc
3.padStart(8, forceSign: true), // + 00000003
(-125).padStart(8) // - 00000125
].forEach{ print($0) }