Swift、stringWithFormat、%s 给出了奇怪的结果

Swift, stringWithFormat, %s gives strange results

我搜索了一整天的答案,但几乎没有什么能真正回答我的问题。我正在尝试在 Swift 中使用 stringWithFormat,但同时使用 printf 格式字符串。我遇到的实际问题是 %s。无论我如何尝试,我似乎都无法找到原始字符串。

非常感谢任何帮助(或解决方法)。 我已经做过的事情:尝试了 cString 的所有可用编码,尝试创建一个用于此的 ObjC 函数,但是当我将参数从 Swift 传递到同一个 st运行 时%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"

使用 "%1$@" 而不是 "%1$s",并且不使用 cString 调用。

这对我有用:

var str = "Age %2$i, Name: %1$@"
let name = "Michael"
let a = String.init(format: str, name, 1234)

使用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, [=10=], 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, 然后将该数组的 地址 传递给字符串 格式化方法。