简体   繁体   中英

How to force Swift to recognize apostrophe?

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.

someString.replacingOccurrences(...) returns a new string object with apostrophes replaced. The original someString 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 warnings). On my setup, this wouldn't have compiled because of the unused return value.

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.

I had the same issue with 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'"
var modstr = str.replacingOccurences(of: "\u{0027"}, with "") // 
apostrophe
modstr = modstr.replacingOccurences(of: "\u{2018"}, with "") 
// left single quote
modstr = modstr.replacingOccurences(of: "\u{2019"}, with "") 
// right single quote
print(modstr)
// modstr = marks new name is mike

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: "")

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM