填充swift字符串以进行打印

5kgi1eie  于 2022-12-10  发布在  Swift
关注(0)|答案(9)|浏览(173)

我试图打印一个字符串列表,所有字符串都填充到相同的宽度。
在C语言中,我会使用类似printf("%40s", cstr),的字符串,其中cstr是C字符串。
在斯威夫特,我能想到的最好的是:

line += String(format: "%40s",string.cStringUsingEncoding(<someEncoding>))

有没有更好的办法?

lskq00tm

lskq00tm1#

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方法被弃用,并且有许多新的方法来获取子字符串。prefixsuffix或用Range<String.Index>String加下标。
对于前面的扩展,我们可以使用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))
        }
    }
}
b4qexyjb

b4qexyjb2#

对于Swift〉= 3

line += string.padding(toLength: 40, withPad: " ", startingAt: 0)

雨燕〈3
NSString具有stringByPaddingToLength:方法:

line += string.stringByPaddingToLength(40, withString: " ", startingAtIndex: 0)
lmvvr0a8

lmvvr0a83#

第一个
为了复制与padding(toLength:, withPad:, startingAt:)相同的行为,我们可以向RangeReplaceableCollection添加rotateTo left功能

extension RangeReplaceableCollection {
    func rotatingLeft(positions: Int) -> SubSequence {
        let index = self.index(startIndex, offsetBy: positions, limitedBy: endIndex) ?? endIndex
        return self[index...] + self[..<index]
    }
}

并如下实现:
第一个

j91ykkif

j91ykkif4#

将所有字符串格式的代码放入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+++++++"
e37o9pze

e37o9pze5#

以下两个函数返回一个填充到给定宽度的字符串,左对齐或右对齐。它是纯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)
    }
}
o75abkj4

o75abkj46#

对于左填充,可以使用双反转技巧:

String(String(s.reversed()).padding(toLength: 5, withPad: "0", startingAt: 0).reversed())

当然,您可以将其 Package 为扩展:

extension String {
    func leftPadding(toLength: Int, withPad: String) -> String {
        String(String(reversed()).padding(toLength: toLength, withPad: withPad, startingAt: 0).reversed())
    }
}
bksxznpy

bksxznpy7#

这是我的解决方案,特定于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())
    }
}
jutyujz0

jutyujz08#

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) }
snvhrwxg

snvhrwxg9#

雨燕五:
我只是花了一个尴尬的时间玩这个相同的问题。

let short = "ab"
String(repeating: "0", count: 8 - short.count).appending(short)
// 000000ab

相关问题