Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace occurrences of NSString - iPhone

I have a long NSString in which I m trying to replace special characters. Part of my string looks like this:

"veau (c\u00f4telette)","veau (filet)","agneau (gigot)","agneau (c\u00f4telette)","b**\u0153**uf (hach\u00e9)","porc (hach\u00e9)" 

I would like to replace all the \u0153 with "oe". I've tried:

[response stringByReplacingOccurrencesOfString:@"\u0153" withString:@"oe"]; 

but it doesn't work.... I don't understand why!

like image 328
ncohen Avatar asked Mar 22 '10 12:03

ncohen


People also ask

What does NSString mean?

A static, plain-text Unicode string object that bridges to String ; use NSString when you need reference semantics or other Foundation-specific behavior.

How do you replace a character in a string in Objective C?

To replace a character in objective C we will have to use the inbuilt function of Objective C string library, which replaces occurrence of a string with some other string that we want to replace it with.

How do I change the first character of a string in Swift?

When I remove the NSMakeRange and change it to nil, it works, but it replaces all the &'s in the string. When you pass nil as the range , of course it will replace all the & characters as you are using stringByReplacingOccurrencesOfString . I get that, I just wanted to tell that I got that working.


2 Answers

The backslash is an escape character, so if you want to specify the actual backslash character in a string literal, you need to use two backslashes.

NSString *new = [old stringByReplacingOccurrencesOfString: @"\\u0153" withString:@"oe"]; 
like image 77
Josh Freeman Avatar answered Sep 28 '22 04:09

Josh Freeman


NSString is immutable, so the function generates a new string that you have to store:

NSString *new = [old stringByReplacingOccurrencesOfString:@"\u0153" withString:@"oe"]; 
like image 27
eWolf Avatar answered Sep 28 '22 03:09

eWolf