20

如何从 NSString中删除开头和结尾的新行\n 。

例如

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

输出:

@"Hi\nHow are you\nToday."

谢谢。

4

4 回答 4

54

使用nsstring的 stringByTrimmingCharactersInSet 方法,该方法返回一个新字符串,该字符串是通过从给定字符集中包含的接收器字符的两端删除而生成的。

迅速

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

Objective-C

  yourString = [yourString stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]]
于 2012-06-18T08:30:14.410 回答
14
NSString *string = @"\n \n  new lines or white spaces in front and at the end \n \n ";
NSString *trimmedString = [string stringByTrimmingCharactersInSet:
                                  [NSCharacterSet whitespaceAndNewlineCharacterSet]];
于 2012-06-18T09:01:57.333 回答
1

斯威夫特 3.0

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

输出 "your string"

于 2017-11-14T11:21:04.373 回答
1

试试这个它对我有用,

  NSString *trimmedValue = [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

希望这会有所帮助。

于 2018-10-01T05:29:48.963 回答