标签:ios
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:@"-"]);
答应结果:
ax@d-s#@sfn$-`SF$$%x^(#e{]e
NSCharacterSet
实例应用:
一、过滤字符串开始位置和结束位置的空格
1 NSString *testString = @" my name is wang tianqiao ";
2
3 NSString *cString = [testString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
4 NSLog(@"cString is %@",cString);
本来想写一个查找替换敏感词语的一个小方法,在网络上找了很久,确实现存方法有点乏力!还是自己动手吧!通过查看API,然后,知道对字符串的操作,可以使用两个类:NSCharacterSet和NSString来操作!
废话不多说了,贴代码:
1.去除首尾的空白符号
NSString *strMsg=@"我爱北京天安门";
id cs=
[NSCharacterSet characterSetWithCharactersInString:@"天门"];
NSString *strResult = [strMsg stringByTrimmingCharactersInSet:[NSCharacterSet
whitespaceCharacterSet]];
2.去掉首尾指定的字符集
NSString *strMsg=@"我爱北京天安门";
id cs=
[NSCharacterSet characterSetWithCharactersInString:@"天门"];
NSString *strResult=[strMsg stringByTrimmingCharactersInSet:cs];
3.去除指定的字符集
NSString *strMsg=@"我爱北京天安门";
NSCharacterSet *cs= [NSCharacterSet characterSetWithCharactersInString:@"天门"];
NSMutableString *theString=[NSMutableString stringWithString:strMsg];
NSString *strResult=
[self clearnIllegitCharacters:theStringandCharacterSet:cs];
// 清除敏感词语,根据给定的字符串&字符集
- (NSString *)clearnIllegitCharacters:(NSMutableString *)originString
andCharacterSet:(NSCharacterSet *)cs{
NSString *strResult=nil;
NSRange range2;
do {
range2=[originString rangeOfCharacterFromSet:cs options:NSLiteralSearch];
if (range2.location!=NSNotFound)
{
// [originString deleteCharactersInRange:range2];
[originString replaceCharactersInRange:range2 withString:@"*"];
}
} while (range2.location!=NSNotFound);
strResult=[[NSString alloc] initWithString:originString];
return strResult;
}
NSCharacterSet
标签:ios
原文地址:http://blog.csdn.net/longshiqing14/article/details/45249291