string = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
是個(gè)你需要牢牢記住的方法。它經(jīng)常會(huì)傳入 [NSCharacterSet whitespaceCharacterSet] 或 [NSCharacterSet whitespaceAndNewlineCharacterSet] 來(lái)刪除輸入字符串的頭尾的空白符號(hào)。
需要重點(diǎn)注意的是匀伏,這個(gè)方法僅僅去除了開頭和結(jié)尾的指定字符集中連續(xù)字符恤溶。這就是說(shuō)异赫,如果你想去除單詞之間的額外空格,請(qǐng)看下一步泊业。
假設(shè)你去掉字符串兩端的多余空格之后颅眶,還想去除單詞之間的多余空格油讯,這里有個(gè)非常簡(jiǎn)便的方法:
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: 在空格處將字符串分割成一個(gè)
NSArray;再用一個(gè) NSPredicate去除空串沈跨;最后由捎,用 NSArray -componentsJoinedByString:
用單個(gè)空格符將數(shù)組重新拼成字符串。注意:這種方法僅適用于英語(yǔ)這種用空格分割的語(yǔ)言饿凛。