Is there a straightforward way in Swift for adding quotation marks to a String? The quotation marks should localize properly (see https://en.wikipedia.org/wiki/Quotation_mark) based on the user's language settings. I'd like to show the string in a UILabel after adding the quotes.
For instance:
var quote: String! quote = "To be or not to be..." // one or more lines of code that add localized quotation marks
For a French user: «To be or not to be...»
For a German user: To be or not to be...
You place your string within quotation marks ( " ) and surround that with number signs ( # ). For example, printing the string literal #"Line 1\nLine 2"# prints the line feed escape sequence ( \n ) rather than printing the string across two lines. let string = #"A string with "double quotes" in it.
Double Quotes inside verbatim strings can be escaped by using 2 sequential double quotes "" to represent one double quote " in the resulting string. var str = @"""I don't think so,"" he said. "; Console. WriteLine(str);
Using escape character for single quotes \' = ' and interpolation ( \() )for variables you can achieve this in one string.
To remove double quotes just from the beginning and end of the String, we can use a more specific regular expression: String result = input. replaceAll("^\"|\"$", ""); After executing this example, occurrences of double quotes at the beginning or at end of the String will be replaced by empty strings.
Using the information from http://nshipster.com/nslocale/:
let locale = NSLocale.currentLocale() let qBegin = locale.objectForKey(NSLocaleQuotationBeginDelimiterKey) as? String ?? "\"" let qEnd = locale.objectForKey(NSLocaleQuotationEndDelimiterKey) as? String ?? "\"" let quote = qBegin + "To be or not to be..." + qEnd print(quote)
Sample results:
Locale Output de „To be or not to be...“ en “To be or not to be...” fr «To be or not to be...» ja 「To be or not to be...」
I don't know if the begin/end delimiter key can be undefined for a locale. In that case the above code would fall back to the normal double-quote "
.
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