Reputation: 378
I am getting a string for a place name back from an API: "Moe\'s Restaurant & Brewhouse"
. I want to just have it be "Moe's Restaurant & Brewhouse"
but I can't get it to properly format without the \
.
I've seen the other posts on this topic, I've tried placeName?.stringByReplacingOccurrencesOfString("\\", withString: "")
and placeName?.stringByReplacingOccurrencesOfString("\'", withString: "'")
. I just can't get anything to work. Any ideas so I can get the string how I want it without the \
? Any help is greatly appreciated, thanks!!
Upvotes: 3
Views: 3131
Reputation: 437482
You report that the API is returning "Moe\'s Restaurant & Brewhouse"
. More than likely you are looking at a Swift dictionary or something like that and it is showing you the string literal representation of that string. But depending upon how you're printing that, the string most likely does not contain any backslash.
Consider the following:
let string = "Moe's"
let dictionary = ["name": string]
print(dictionary)
That will print:
["name": "Moe\'s"]
It is just showing the "string literal" representation. As the documentation says:
String literals can include the following special characters:
- The escaped special characters
\0
(null character),\\
(backslash),\t
(horizontal tab),\n
(line feed),\r
(carriage return),\"
(double quote) and\'
(single quote)- An arbitrary Unicode scalar, written as
\u{n}
, wheren
is a1
–8
digit hexadecimal number with a value equal to a valid Unicode code point
But, note, that backslash before the '
in Moe\'s
is not part of the string, but rather just an artifact of printing a string literal with an escapable character in it.
If you do:
let string2 = dictionary["name"]!
print(string2)
It will show you that there is actually no backslash there:
Moe's
Likewise, if you check the number of characters:
print(dictionary["name"]!.characters.count)
It will correctly report that there are only five characters, not six.
(For what it's worth, I think Apple has made this far more confusing than is necessary because it sometimes prints strings as if they were string literals with backslashes, and other times as the true underlying string. And to add to the confusion, the single quote character can be escaped in a string literal, but doesn't have to be.)
Note, if your string really did have a backslash in it, you are correct that this is the correct way to remove it:
someString.stringByReplacingOccurrencesOfString("\\", withString: "")
But in this case, I suspect that the backslash that you are seeing is an artifact of how you're displaying it rather than an actual backslash in the underlying string.
Upvotes: 4