Swift: using% s in String (format: ...)

I would like to format a string with a different string like this:

var str = "Hello, playground"
print (String(format: "greetings %s", str))

      

This leads to this beautiful result:

hi ε“° ૧

I tried with% @ and it works, but since I am getting the format string from another programming language, I would like to use the% s tag if possible. Is there a way?

+11


source to share


2 answers


Ok, I've replaced% s with% @. Python is my friend.



Thank!

+9


source


Solution 1: change the format

If the format is from a reliable external source, you can convert it to replace the occurrences %s

with %@

:

So instead of:

String(format: "greetings %s", str)

      

You do:

String(format: "greetings %s".replacingOccurrences(of: "%s", with: "%@"), str)

      


Solution 2: changing the line



If the format is complex , simple substitution will not work. For example:

  • when using a specifier with a numeric character sequence: %1$s

  • when using the "%" character followed by "s": %%s

  • when using the width modifier: %-10s

In cases like this, we need to stick to the C line.

So instead of:

String(format: "greetings %s", str)

      

You do:

str.withCString {
    String(format: "greetings %s", $0)
}

      

+3


source







All Articles