I want to append a string to a NSMutableString using appendFormat, inserting white spaces to get a minimum length for my string.
In objective-c, i just used
[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.
Is there anyone who knows why that happens, and what I should do?
Thank you guys!
The Swift string is one character long, as expected. The NSString says it has a length of seven — this matches with the length of the Swift string's utf16 view, since NSStrings are backed by UTF-16: 09:02 The Swift string's unicodeScalars view returns a count of four.
String interpolation is a way to construct a new String value from a mix of constants, variables, literals, and expressions by including their values inside a string literal. You can use string interpolation in both single-line and multiline string literals.
AppendFormat(IFormatProvider, String, Object) Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Each format item is replaced by the string representation of a single argument using a specified format provider.
You should use String's method stringByPaddingToLength() as follow:
let anyString = "MyString"
let padedString = anyString.stringByPaddingToLength(12, withString: " ", startingAtIndex: 0) // "MyString "
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With