0

I am being provided a string that may have a unicode apostrophe in it (\u2019) and I must replace it with a standard apostrophe (plain old "'"). I usually use stringByReplacingOccurrencesOfString to do this kind of thing but trying this does not work:

sMyString = [sMyString stringByReplacingOccurrencesOfString:@"\\u2019" withString:@"'"];

Makes sense that it didn't work I guess since the actual values representing the apostrophe internally in the NSString will be numeric. Anyone know how to do this?

Alyoshak
  • 2,696
  • 10
  • 43
  • 70
  • Does the string have an actual `’` character or does it have the characters \, `u`, `2`, `0`, `1`, and `9`? – rmaddy Feb 09 '16 at 23:47
  • When I use po sMyString in Xcode's console it appear as an actual ' character, though curved as you have shown it. However, when that string is part of a dictionary and I use po to print out the dictionary it displays the sequence, so Mama's boy looks like: Mama\u2019s boy. That's how I discovered it actually. – Alyoshak Feb 09 '16 at 23:57
  • Logging a dictionary results in `\uxxxx` output for lots of characters. That's just a stupid decision by Apple to confuse developers. Sounds like your string has the actual quote character. My posted answer should do what you want. – rmaddy Feb 10 '16 at 00:00

2 Answers2

1

If sMyString has the actual character then either do:

sMyString = [sMyString stringByReplacingOccurrencesOfString:@"\u2019" withString:@"'"];

or:

sMyString = [sMyString stringByReplacingOccurrencesOfString:@"’" withString:@"'"];

Both of these actually compile to the same code. The \u2019 is replaced by during compilation.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Absolutely correct. Dang. I had the extra backslash in there which is why it wasn't finding it. Removed it so it looked like your code and worked like a champ. Many thanks. – Alyoshak Feb 10 '16 at 00:03
  • With the extra backslash, the match will only work if the string contains the actual text `\u2019`. – rmaddy Feb 10 '16 at 00:05
0
sMyString = [sMyString stringByReplacingOccurrencesOfString:@"\U2019" withString:@"'"];

Do not use \U2019, it makes an error.

Lotus91
  • 1,127
  • 4
  • 18
  • 31