I would like to format a string with another string like this:
var str = "Hello, playground"
print (String(format: "greetings %s", str))
This leads to this beautiful result:
greetings 哰૧
I tried with %@ and it works but, as I'm getting format string from another programming language, I would like, if possible to use the %s tag. Is there a way to ?
%d means number. %0nd means zero-padded number with a length. You build n by subtraction in your example. %s is a string. Your format string ends up being this: "%03d%s", 0, "Apple"
%s in the format string is replaced with the content of language . %s is a format specifier. Similarly, %x is replaced with the hexadecimal value of number in String. format("Number: %x", number) .
If the format is from a reliable external source, you can convert it to replace occurences of %s
with %@
:
So, instead of:
String(format: "greetings %s", str)
You do:
String(format: "greetings %s".replacingOccurrences(of: "%s", with: "%@"), str)
If the format is complex, a simple replacement won't work. For instance:
%1$s
%%s
%-10s
In similar cases, we need to stick to a C string.
So instead of:
String(format: "greetings %s", str)
You do:
str.withCString {
String(format: "greetings %s", $0)
}
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