1.NSCharacterSet其实是许多字符或者数字或者符号的组合,用NSCharacterSet处理字符串
//NSCharacterSet其实是许多字符或者数字或者符号的组合,在网络处理的时候会用到
NSMutableCharacterSet *base = [NSMutableCharacterSet lowercaseLetterCharacterSet];
//字母
NSCharacterSet *decimalDigit = [NSCharacterSet decimalDigitCharacterSet]; //十进制数字
[base formUnionWithCharacterSet:decimalDigit]; //字母加十进制
NSString *string = @"ax@d5s#@sfn$5`SF$$%x^(#e{]e";
//用上面的base隔开string然后组成一个数组,然后通过componentsJoinedByString,来连接成一个字符串
//非 字母加十进制
NSLog(@"%@",[[string componentsSeparatedByCharactersInSet:base] componentsJoinedByString:@"-"]);
[base invert];
NSLog(@"%@",[[string componentsSeparatedByCharactersInSet:base] componentsJoinedByString:@"-"]);
2.去掉字符串的头尾的空格
//NSString -stringByTrimmingCharactersInSet: 是个你需要牢牢记住的方法。它经常会传入 NSCharacterSet +whitespaceCharacterSet 或 +whitespaceAndNewlineCharacterSet 来删除输入字符串的头尾的空白符号。
NSString *str=@" my name is kfc ";
NSLog(@"%lu",str.length);
NSLog(@"%@",[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]);
NSLog(@"%lu",[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]].length);
3. 挤压空格
//假设你去掉字符串两端的多余空格之后,还想去除单词之间的多余空格
NSString *str=@" my name is kfc ";
str=[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSArray *components=[str componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
components=[components filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF<>''",str]];
str=[components componentsJoinedByString:@""];
NSLog(@"%@",str);