Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove beginning and trailing new line characters from NSString

How can one remove only the beginning and trailing new line \n from a NSString.

For e.g.

@"\n\n\n\Hi\nHow are you\nToday.\n\n\n\n"

output:

@"Hi\nHow are you\nToday."

Thanks.

like image 918
southpark Avatar asked Jun 18 '12 08:06

southpark


3 Answers

Use stringByTrimmingCharactersInSet method of nsstring which Returns a new string made by removing from both ends of the receiver characters contained in a given character set.

Swift

yourString = yourString.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)

Objective-C

  yourString = [yourString stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]]
like image 97
Paresh Navadiya Avatar answered Oct 17 '22 11:10

Paresh Navadiya


NSString *string = @"\n \n  new lines or white spaces in front and at the end \n \n ";
NSString *trimmedString = [string stringByTrimmingCharactersInSet:
                                  [NSCharacterSet whitespaceAndNewlineCharacterSet]];
like image 14
Shyam Bhat Avatar answered Oct 17 '22 12:10

Shyam Bhat


Swift 3.0

var yourString = "\n your string \n"
yourString = yourString.trimmingCharacters(in: .whitespacesAndNewlines)

Output "your string"

like image 1
Abhishek Jain Avatar answered Oct 17 '22 12:10

Abhishek Jain