jroyce
jroyce

Reputation: 2148

How do I remove new line characters from a string?

I need to strip away any new line characters from a string. I tried the stringByReplacingOccurencesOfString method below. What is the correct method to do this in Objective C?

[textLine stringByReplacingOccurrencesOfString:@"\n" withString:@""];

Upvotes: 1

Views: 1727

Answers (2)

Jess
Jess

Reputation: 3146

stringByReplacingOccurrencesOfString does not modify textLine

NSString *strippedTextLine = [textLine stringByReplacingOccurrencesOfString:@"\n" withString:@""];

Or

NSString *textLine = @"My cool text\n";
textLine = [textLine stringByReplacingOccurrencesOfString:@"\n" withString:@""];

Upvotes: 3

Tommy Devoy
Tommy Devoy

Reputation: 13549

NSString *textWithNewLinesRemoved = [textLine stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];

Upvotes: 5

Related Questions