我搜索了一整天的答案,但几乎没有什么能真正回答我的问题。我正在尝试在 Swift 中使用 stringWithFormat,但同时使用 printf 格式字符串。我遇到的实际问题是 %s。无论我如何尝试,我似乎都无法找到原始字符串。
非常感谢任何帮助(或解决方法)。 我已经做过的事情:为 cString 尝试了所有可用的编码,尝试创建一个 ObjC 函数来用于此,但是当我从 Swift 传递参数时,我遇到了与 %s 相同的奇怪问题,即使在 ObjC 中进行了硬编码函数体似乎打印了实际正确的字符串。
请在下面找到示例代码。
非常感谢!
var str = "Age %2$i, Name: %1$s"
let name = "Michael".cString(using: .utf8)!
let a = String.init(format: str, name, 1234)
我想预期的结果很清楚,但是我得到的是这样的而不是正确的名称:
"Age 1234, Name: ÿQ5"
最佳答案
使用 withCString()
调用带有 C 字符串的函数
Swift 字符串的表示。还要注意 %ld
是正确的
Swift Int
的格式(可以是 32 位或 64 位整数)。
let str = "Age %2$ld, Name: %1$s"
let name = "Michael"
let a = name.withCString { String(format: str, $0, 1234) }
print(a) // Age 1234, Name: Michael
另一种可能的选择是创建一个(临时)副本
C字符串表示
(使用 Swift 字符串在传递给采用 const char *
参数的 C 函数时自动转换为 C 字符串的事实,
如 String value to UnsafePointer<UInt8> function parameter behavior 中所述):
let str = "Age %2$ld, Name: %1$s"
let name = "Michael"
let nameCString = strdup(name)!
let a = String(format: str, nameCString, 1234)
print(a)
free(nameCString)
我假设您的代码没有按预期工作,因为name
(在您的代码中具有类型 [CChar]
)桥接到 NSArray
,
然后将该数组的地址传递给字符串
格式化方法。
关于Swift、stringWithFormat、%s 给出了奇怪的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42984338/