xcode 如何使用 appendFormat 在 Swift 中格式化字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29762201/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use appendFormat to format a string in Swift?
提问by kobuchi
I want to append a string to a NSMutableString using appendFormat, inserting white spaces to get a minimum length for my string.
我想使用 appendFormat 将字符串附加到 NSMutableString,插入空格以获得字符串的最小长度。
In objective-c, i just used
在objective-c中,我刚刚使用
[text.mutableString appendFormat:@"%-12s", "MyString"];
and I would get
我会得到
"MyString "
But in Swift, I tried
但在斯威夫特,我试过
text.mutableString.appendFormat("%-12s", "MyString")
and I get everything, but not "MyString ". It appears some random characters that I do not know where it came from.
我得到了一切,但不是“MyString”。出现一些随机字符,我不知道它来自哪里。
Is there anyone who knows why that happens, and what I should do?
有没有人知道为什么会发生这种情况,我应该怎么做?
Thank you guys!
谢谢你们!
采纳答案by Leo Dabus
You should use String's method stringByPaddingToLength()as follow:
您应该使用 String 的方法stringByPaddingToLength()如下:
let anyString = "MyString"
let padedString = anyString.stringByPaddingToLength(12, withString: " ", startingAtIndex: 0) // "MyString "
回答by Adam S
Through Ken's explanation that a Swift String object is notequivalent to the Objective-C C-style string (a null-terminated array of char
) I found this answerwhich shows how to convert a Swift String object into a Cstring, which the %-12s
formatting works correctly on.
通过 Ken 的解释,即 Swift String 对象不等同于 Objective-C C 样式字符串(以空结尾的数组char
),我找到了这个答案,该答案显示了如何将 Swift String 对象转换为 Cstring,%-12s
格式正确在。
You can use your existing formatting string as follows:
您可以使用现有的格式字符串,如下所示:
text.mutableString.appendFormat("%-12s", ("MyString" as NSString).UTF8String)
Some examples:
一些例子:
var str = "Test"
str += String(format:"%-12s", "Hello")
// "Test–y? " (Test, a dash, 11 random characters)
var str2 = "Test"
str2 += String(format:"%-12@", "Hello")
// "TestHello" (no padding)
var str3 = "Test"
str3 += String(format:"%-12s", ("Hello" as NSString).UTF8String)
// "TestHello " ('Hello' string is padded out to 12 chars)
回答by Ken Thomases
Try:
尝试:
text.mutableString.appendFormat("%-12@", "MyString")
In Swift, "MyString"
is a String
object. The %s
format specifier causes appendFormat()
to interpret its argument as a C-style string (a buffer of char
terminated by a null char
).
在 Swift 中,"MyString"
是一个String
对象。该%s
格式说明使appendFormat()
解释其作为C风格字符串参数(的缓冲器char
以空终止char
)。
In Objective-C, "MyString"
is just such a C-style string. You would have to prefix it with an @
to get an NSString
object (@"MyString"
).
在Objective-C中,"MyString"
就是这样一个C风格的字符串。您必须在它前面加上前缀@
才能获得NSString
对象 ( @"MyString"
)。
回答by muneeb
let space: Character = " "
text = "MyString" + String(count: 12, repeatedValue: space)