Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift : use of %s in String(format: ...)

Tags:

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 ?

like image 579
Julien Avatar asked Jul 12 '17 21:07

Julien


People also ask

What is %d and %s in Java?

%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"

What is %s format in Java?

%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) .


1 Answers

Solution 1: changing the format

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)

Solution 2: changing the string

If the format is complex, a simple replacement won't work. For instance:

  • when using a specifier with a numeric character sequence: %1$s
  • when using the '%' character followed by an 's': %%s
  • when using a width modifier: %-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)
}
like image 120
Cœur Avatar answered Sep 29 '22 21:09

Cœur