刪除前導和尾隨空格

NSString *someString = @"   Objective-C Language  \n";
NSString *trimmedString = [someString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
//Output will be - "Objective-C Language"

方法 stringByTrimmingCharactersInSet 返回通過從給定字符集中包含的 String 字元的兩端刪除而生成的新字串。

我們也可以只刪除空格或換行符

// Removing only WhiteSpace
NSString *trimmedWhiteSpace = [someString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
//Output will be - "Objective-C Language  \n"

// Removing only NewLine
NSString *trimmedNewLine = [someString stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
//Output will be - "   Objective-C Language  "