简体   繁体   中英

Remove leading and trailing newline characters from NSString

I have an NSString which consists of the text a user has entered into a UITextView . As a result, the string may have leading and trailing newline characters, along with newline characters within the string (if they hit the Return key to type on a new line). I would like to remove any newline characters from the beginning and end of the string, leaving any within the string intact.

What would be the best way to go about this?

text = [text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

This trims also whitespace. If you want to keep whitespace, just use the newlineCharacterSet instead.

Edited, as per @ghettopia correct suggestion about using the newlineCharacterSet instead of creating. Custom one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM