美文网首页
NSCharacterSet

NSCharacterSet

作者: O_BeiBei | 来源:发表于2016-12-30 11:01 被阅读0次

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:

用单个空格符将数组重新拼成字符串。注意:这种方法仅适用于英语这种用空格分割的语言。

相关文章

网友评论

      本文标题:NSCharacterSet

      本文链接:https://www.haomeiwen.com/subject/qwkmvttx.html