How to use appendFormat to format a string in Swift?

I want to add a string to NSMutableString using appendFormat, inserting spaces to get the minimum length for my string.

In objective-c, I just used

[text.mutableString appendFormat:@"%-12s", "MyString"]; 

and i get

 "MyString " 

But in Swift I tried

 text.mutableString.appendFormat("%-12s", "MyString") 

and I get everything but not "MyString". There seem to be some random characters that I don’t know where they came from.

Is there anyone who knows why this is happening, and what should I do?

Thanks guys!

+7
ios xcode swift nsmutablestring
source share
4 answers

You should use the String method stringByPaddingToLength () as follows:

 let anyString = "MyString" let padedString = anyString.stringByPaddingToLength(12, withString: " ", startingAtIndex: 0) // "MyString " 
+4
source share

Through Ken's explanation that the Swift String object is not equivalent to the Objective-C C-style string (a char -terminated array), I found this answer that shows how to convert the Swift String object to Cstring, which formatting %-12s works correctly.

You can use the existing format 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) 
+3
source share

Try:

 text.mutableString.appendFormat("% -12@ ", "MyString") 

In Swift, the "MyString" object is a String object. The %s format appendFormat() forces appendFormat() interpret its argument as a C-style string ( char buffer terminated by char zero).

In Objective-C, "MyString" is just such a C-style string. You will need to prefix it with @ to get an NSString ( @"MyString" ).

+2
source share
  let space: Character = " " text = "MyString" + String(count: 12, repeatedValue: space) 
+1
source share

All Articles