ios - 如何使用 appendFormat 在 Swift 中格式化字符串?

标签 ios xcode swift nsmutablestring

我想使用 appendFormat 将字符串附加到 NSMutableString,插入空格以获得我的字符串的最小长度。

在 objective-c 中,我只是使用

[text.mutableString appendFormat:@"%-12s", "MyString"];

我会得到

"MyString    "

但是在 Swift 中,我试过了

text.mutableString.appendFormat("%-12s", "MyString")

我得到了一切,但不是“MyString”。出现了一些不知从何而来的随机字符。

有谁知道为什么会这样,我应该怎么做?

谢谢大家!

最佳答案

你应该使用String的方法stringByPaddingToLength()如下:

let anyString = "MyString"
let padedString = anyString.stringByPaddingToLength(12, withString: " ", startingAtIndex: 0)  // "MyString    "

关于ios - 如何使用 appendFormat 在 Swift 中格式化字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29762201/

相关文章:

javascript - 如何在 javascript 中取消选择/取消焦点文本字段

ios - 在 Swift QueryClosure 中将数组添加到数组

objective-c - iOS 如何处理数据库更新所需的时间

ios - 如何在 Swift/Objective C 中从 HTTP 请求返回数据

ios - ATS 将在 IOS 应用程序中强制执行。简单的饲料呢?

ios - NSMethodSignature 和 NSInvocation 等价于 swift 2

ios - 从选择器 View 访问 viewController

ios - 在设备上运行但不在 Swift 模拟器中运行时的断点

ios - 添加 Google 移动插页式广告 Swift

ios - 找不到 Amazon Cognito 身份池