0

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.

  • The last one should work. Can you show the string input? Maybe it's a full width apostrophe? – Sweeper Mar 28 '20 at 11:07
  • 3
    I'd print the original string. There are many characters looking quite similar to an apostrophe. Like ‘this’. No apostrophe here. – gnasher729 Mar 28 '20 at 11:07
  • wellingtons' is the input string. I am typing the same apostrophe from my keyboard into the code and into the input string. – Ludovico Verniani Mar 28 '20 at 18:31

4 Answers4

2

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.

Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
gnasher729
  • 51,477
  • 5
  • 75
  • 98
  • I understand this, my original code sets a new string equal to replacingOccurences. That new string does not have the apostrophe removed. – Ludovico Verniani Mar 28 '20 at 18:32
2

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: "")
Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
ThomasFr
  • 65
  • 7
  • This is effectively the same as [Mark’s answer](https://stackoverflow.com/a/68431775/3025856) from a couple of months ago. The only difference is that you chose to use the literal character instead of the encoded character. But it’s functionally identical. – Jeremy Caney Sep 16 '21 at 00:36
1

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
Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
Markv07
  • 196
  • 1
  • 8
0

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