string = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
是個你需要牢牢記住的方法。它經常會傳入 [NSCharacterSet whitespaceCharacterSet] 或 [NSCharacterSet whitespaceAndNewlineCharacterSet] 來刪除輸入字符串的頭尾的空白符號。
需要重點注意的是,這個方法僅僅去除了開頭和結尾的指定字符集中連續字符。這就是說,如果你想去除單詞之間的額外空格,請看下一步。
假設你去掉字符串兩端的多余空格之后,還想去除單詞之間的多余空格,這里有個非常簡便的方法:
NSString *string = @"Lorem? ? ipsum dolar?? sit? amet.";
string = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSArray *components = [string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
components = [components filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self <> ''"]];
string = [components componentsJoinedByString:@" "];
首先,刪除字符串首尾的空格;然后用
NSString -componentsSeparatedByCharactersInSet: 在空格處將字符串分割成一個
NSArray;再用一個 NSPredicate去除空串;最后,用 NSArray -componentsJoinedByString:
用單個空格符將數組重新拼成字符串。注意:這種方法僅適用于英語這種用空格分割的語言。