NSString -stringByTrimmingCharactersInSet: 是個你需要牢牢記住的方法滋觉。它經(jīng)常會傳入 NSCharacterSet +whitespaceCharacterSet 或 +whitespaceAndNewlineCharacterSet 來刪除輸入字符串的頭尾的空白符號蹈集。
需要重點注意的是辩块,這個方法 僅僅 去除了 開頭 和 結尾 的指定字符集中連續(xù)字符闹击。這就是說尚氛,如果你想去除單詞之間的額外空格视粮,請看下一步采桃。
假設你去掉字符串兩端的多余空格之后戏阅,還想去除單詞之間的多余空格昼弟,這里有個非常簡便的方法:
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: 用單個空格符將數(shù)組重新拼成字符串芭逝。注意:這種方法僅適用于英語這種用空格分割的語言。