Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove "\n" from NSString

My json is returning this :

address = "129 City Road

\nShoreditch

\nLondon EC1V 1JB";

I want to remove the "\n". Because I want to display it in one line.

I tried following:

NSString * newReplacedString = [string stringByReplacingOccurrencesOfString:@"\n" withString:@""];

NSString * newReplacedString = [string stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];

Both result same:

Result

900 N Michigan Avenue

Chicago

Illinois 60611

If I tried this

NSString *s = [string stringByReplacingOccurrencesOfString:@"\n" withString:@"\\n"];

Result

900 N Michigan Avenue

\nChicago

\nIllinois 60611

Please suggest.

like image 385
Priyanka Chhetri Avatar asked Jun 11 '12 10:06

Priyanka Chhetri


3 Answers

Try it :

NSString *address = @"129 City Road \nShoreditch \nLondon EC1V 1JB";    
address = [address stringByReplacingOccurrencesOfString:@"\n" withString:@""];
address = [address stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];

This worked and i got the output like :

129 City Road Shoreditch London EC1V 1JB
like image 124
Mansi Panchal Avatar answered Jan 01 '23 09:01

Mansi Panchal


It looks like the \n is a literally in you string and not as a newline character, then you need to escape the \, like \\n:

NSString * newReplacedString = [string stringByReplacingOccurrencesOfString:@"\\n" withString:@""];

NSString * newReplacedString = [string stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
like image 31
rckoenes Avatar answered Jan 01 '23 07:01

rckoenes


NSString *newString = [str stringByReplacingOccurrencesOfString:@"\r\n" withString:@""];

For those who may be looking for the answer. Try the above once. It worked for me.

like image 37
Arunavh Krishnan Avatar answered Jan 01 '23 07:01

Arunavh Krishnan