NSCharacterSet去除字符串中的空格、删除指定\任意字符集
一.去除首尾的空格
/** 1.去除首尾的空格*/
NSString *strMsg=@" 简书作者:CoderZb ";
NSString *strResult = [strMsg stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSLog(@"去除空格前:%@",strMsg);
NSLog(@"去除空格后:%@",strResult);
二.去除连续的字符集
/** 2.去除指定的字符集*/
NSString *strMsg2=@"简书作者:CoderZb";
id cs= [NSCharacterSet characterSetWithCharactersInString:@"简书作者:"];
NSString *strResult2=[strMsg2 stringByTrimmingCharactersInSet:cs];
NSLog(@"去除之后的结果:%@",strResult2);
三.去除任意的字符集(连续、非连续都可)
/** 3.删除任意的字符集*/
NSString *strMsg=@"简书作者:CoderZb";
NSCharacterSet *cs= [NSCharacterSet characterSetWithCharactersInString:@"简者Cdb"];
NSMutableString *theString=[NSMutableString stringWithString:strMsg];// 将strMsg变为可变字符串
NSString *strResult= [self clearnIllegitCharacters:theString andCharacterSet:cs];
NSLog(@"删除任意的字符集的结果:%@",strResult);
// 清除敏感词语
- (NSString *)clearnIllegitCharacters:(NSMutableString *)originString andCharacterSet:(NSCharacterSet *)cs{
NSString *strResult=nil;
NSRange range2;
do {
range2=[originString rangeOfCharacterFromSet:cs options:NSLiteralSearch];
if (range2.location!=NSNotFound) {// range2.location不为NSNotFound,就执行{}
// [originString deleteCharactersInRange:range2];// 删除range2代表的字符集
[originString replaceCharactersInRange:range2 withString:@"*"];// 用星号替换掉range2代表的字符集
}
} while (range2.location!=NSNotFound);// range2.location不为NSNotFound,就执行do{},直至等于NSNotFound,就不再执行do{}
// 可变字符串变为不可变
strResult=[[NSString alloc] initWithString:originString];
return strResult;
}
[originString replaceCharactersInRange:range2 withString:@"*"];// 用星号替换掉range2代表的字符集
[originString deleteCharactersInRange:range2];// 删除range2代表的字符集
四.字符串分割(常用)方式1:
#define kAlphaNum @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
NSString *str = @"简书作者:Coder#Z@b";
NSCharacterSet *cs;
// invertedSet方法是取反字符。所以cs的值为:除了kAlphaNum里的字符,其余的任何字符都是cs
cs = [[NSCharacterSet characterSetWithCharactersInString:kAlphaNum] invertedSet];
// 将str按cs分割成数组(既然能分割,说明cs是str的子集,并且cs中的字符不会在str中出现,相当于str中删除了这些字符),最后将数组按照@""分割成字符串
NSString *filtered = [[str componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
NSLog(@"字符串->数组->字符串 %@", filtered);
四.字符串分割(常用)方式2:
NSString *str = @"简书作者:Coder#Z@b";
//按@"#简书@作者:"将str分离成数组,然后将数组按@"-"拼接成字符串
NSString *filtered = [[str componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"#简书@作者:"]] componentsJoinedByString:@"-"];
NSLog(@"%@", filtered);