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.
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.
yourString = yourString.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)
yourString = [yourString stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]]
NSString *string = @"\n \n new lines or white spaces in front and at the end \n \n ";
NSString *trimmedString = [string stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
Swift 3.0
var yourString = "\n your string \n"
yourString = yourString.trimmingCharacters(in: .whitespacesAndNewlines)
Output "your string"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With