-2

I am trying to parse text and trying to remove some characters.

This doesn't seem to work:

string.replacingOccurrences(of: "‘", with: "'")
string.replacingOccurrences(of: "“", with: "\"")

Any help is resolving this would be excellent!

Thank you.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Mihir
  • 137
  • 2
  • 12
  • 1
    Possible duplicate of [Any way to replace characters on Swift String?](https://stackoverflow.com/questions/24200888/any-way-to-replace-characters-on-swift-string) – MwcsMac Aug 28 '18 at 15:35
  • Just tested in a playground your first example works just fine, what seems to be problem? – inokey Aug 28 '18 at 15:38
  • Its not a duplicate. I know the function that does this. But I am seeing that the string is not being replaced. Hence the question. This is a particular type of smart quote that I want to replace with a "dumb" quote or an apostrophe. Hope this clarifies. – Mihir Aug 28 '18 at 15:39
  • @Mihir Do you save the results they return? – Fabian Aug 28 '18 at 15:40
  • So I tried using the playground to see what is wrong and it turns out that the code cant even find this type of quote mark ‘. I am pasting the results below:var `testString = "After the late Arizonanʼs prolonged absence" var replaced = testString.replacingOccurrences(of: "‘", with: "") //replaced = replaced.replacingOccurrences(of: "'", with: "") print(testString) print(replaced)` After the late Arizonanʼs prolonged absence After the late Arizonanʼs prolonged absence – Mihir Aug 28 '18 at 15:45
  • 1
    Be careful. From your current code: The single quote in `testString` is not the same one a the one you are looking for in `replaceOccurences(of:)`. It's `ʼ` vs `‘`. You can do `let first = "ʼ"; let second = "‘"; do for each one: `let firstData = first.data(encoding: .utf8); print("first: \(data as! NSData)")`, you'll see that the result is different. – Larme Aug 28 '18 at 15:56
  • @Mihir: Don't put the code into the comments, [edit] your question and provide a [mcve]. – Martin R Aug 28 '18 at 15:58
  • @Larme This solved the problem. The quotes are different!!! Thank you for solving this! – Mihir Aug 28 '18 at 16:00

1 Answers1

2

String.replacingOccurrences returns a new instance of the string with the changes made, hence you need to assign and use that new string:

string = string.replacingOccurrences(of: "‘", with: "'")
string = string.replacingOccurrences(of: "“", with: "\"")

Or, perhaps more in style:

string = string.replacingOccurrences(of: "‘", with: "'")
               .replacingOccurrences(of: "“", with: "\"")
David Berry
  • 40,941
  • 12
  • 84
  • 95