How to force Swift to recognize apostrophe?

2k Views Asked by At

I am trying to replace all apostrophe (') characters in a string with another character. I am running this code:

someString.replacingOccurrences(of: apost, with: "a")

I have tried to let apost equal the following:

apost = "\'"
apost = #"'"#
apost = "'"

None of them have removed the apostrophe from someString.

Please let me know if there is a way to get Swift to replace apostrophe's. Thank you.

4

There are 4 best solutions below

1
On

The replacingOccurrences(...) method returns a new string object with the apostrophes replaced. The original someString object isn't changed by this. You need:

someString = someString.replacingOccurences(...)

If that's what's happened, turn more warnings on in Xcode (or look at the warnings). On my setup, this wouldn't have compiled because of the unused return value.

1
On

I had the same issue. It's because the apostrophe is not the right character; it should be a typographic (or “curly”) apostrophe (), not a typewriter (or “straight”) apostrophe ('). Copy and paste the code below, or just the correct apostrophe character:

searchQuery = searchQuery.replacingOccurrences(of: "’", with: "")
0
On

I had the same issue with it not recognizing apostrophies or single quotes. To find and replace them, use the unicode for each character. This worked for me.

let str = "mark's new name is 'mike'"

// apostrophe
var modstr = str.replacingOccurences(of: "\u{0027"}, with "")

// left single quote
modstr = modstr.replacingOccurences(of: "\u{2018"}, with "") 

// right single quote
modstr = modstr.replacingOccurences(of: "\u{2019"}, with "") 

// output
print(modstr)

Output:

marks new name is mike
0
On

You can assign a comparison character for apostrophe as char charToCompare = (char)8217;