Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use appendFormat to format a string in Swift?

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!

like image 407
kobuchi Avatar asked Apr 21 '15 03:04

kobuchi


People also ask

What is difference between string and NSString in Swift?

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.

What is string interpolation in Swift?

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.

How to use AppendFormat in c#?

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.


1 Answers

You should use String's method stringByPaddingToLength() as follow:

let anyString = "MyString"
let padedString = anyString.stringByPaddingToLength(12, withString: " ", startingAtIndex: 0)  // "MyString    "
like image 91
Leo Dabus Avatar answered Oct 23 '22 13:10

Leo Dabus