一.去除首尾的空格
/** 1.去除首尾的空格*/
NSString *strMsg=@" 簡(jiǎn)書作者:CoderZb ";
NSString *strResult = [strMsg stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSLog(@"去除空格前:%@",strMsg);
NSLog(@"去除空格后:%@",strResult);
二.去除連續(xù)的字符集
/** 2.去除指定的字符集*/
NSString *strMsg2=@"簡(jiǎn)書作者:CoderZb";
id cs= [NSCharacterSet characterSetWithCharactersInString:@"簡(jiǎn)書作者:"];
NSString *strResult2=[strMsg2 stringByTrimmingCharactersInSet:cs];
NSLog(@"去除之后的結(jié)果:%@",strResult2);
三.去除任意的字符集(連續(xù)荤牍、非連續(xù)都可)
/** 3.刪除任意的字符集*/
NSString *strMsg=@"簡(jiǎn)書作者:CoderZb";
NSCharacterSet *cs= [NSCharacterSet characterSetWithCharactersInString:@"簡(jiǎn)者Cdb"];
NSMutableString *theString=[NSMutableString stringWithString:strMsg];// 將strMsg變?yōu)榭勺冏址? NSString *strResult= [self clearnIllegitCharacters:theString andCharacterSet:cs];
NSLog(@"刪除任意的字符集的結(jié)果:%@",strResult);
// 清除敏感詞語(yǔ)
- (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,就執(zhí)行{}
// [originString deleteCharactersInRange:range2];// 刪除range2代表的字符集
[originString replaceCharactersInRange:range2 withString:@"*"];// 用星號(hào)替換掉range2代表的字符集
}
} while (range2.location!=NSNotFound);// range2.location不為NSNotFound,就執(zhí)行do{},直至等于NSNotFound,就不再執(zhí)行do{}
// 可變字符串變?yōu)椴豢勺? strResult=[[NSString alloc] initWithString:originString];
return strResult;
}
[originString replaceCharactersInRange:range2 withString:@""];// 用星號(hào)替換掉range2代表的字符集*
[originString deleteCharactersInRange:range2];// 刪除range2代表的字符集
四.字符串分割(常用)方式1:
#define kAlphaNum @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
NSString *str = @"簡(jiǎn)書作者:Coder#Z@b";
NSCharacterSet *cs;
// invertedSet方法是取反字符氧敢。所以cs的值為:除了kAlphaNum里的字符,其余的任何字符都是cs
cs = [[NSCharacterSet characterSetWithCharactersInString:kAlphaNum] invertedSet];
// 將str按cs分割成數(shù)組(既然能分割,說(shuō)明cs是str的子集,并且cs中的字符不會(huì)在str中出現(xiàn),相當(dāng)于str中刪除了這些字符),最后將數(shù)組按照@""分割成字符串
NSString *filtered = [[str componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
NSLog(@"字符串->數(shù)組->字符串 %@", filtered);
四.字符串分割(常用)方式2:
NSString *str = @"簡(jiǎn)書作者:Coder#Z@b";
//按@"#簡(jiǎn)書@作者:"將str分離成數(shù)組,然后將數(shù)組按@"-"拼接成字符串
NSString *filtered = [[str componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"#簡(jiǎn)書@作者:"]] componentsJoinedByString:@"-"];
NSLog(@"%@", filtered);
參考鏈接:http://blog.sina.com.cn/s/blog_7b9d64af0101i9g0.html
參考鏈接:http://blog.csdn.net/lcl130/article/details/41802623
參考鏈接:http://blog.sina.com.cn/s/blog_897dd7be0100teh6.html