比如一个字符串:
NSString * hmutStr = @"(010)*(123)E6(234)**150-1111-^^-1234#"
很多时候,数据之间的传输,我们仅仅只想保留下字符串里面的数字和字母,其他的飞数字字母的符号都得过滤掉,过滤的方法有两种:
方法一:
替代发
使用stringByReplacingOccurrencesOfString这个方法将字符串里的非法字符逐个替代
具体代码如下:
hmutStr = [tempString stringByReplacingOccurrencesOfString:@" " withString:@""];
hmutStr = [tempString stringByReplacingOccurrencesOfString:@"#" withString:@""];
hmutStr = [tempString stringByReplacingOccurrencesOfString:@"*" withString:@""];
hmutStr = [tempString stringByReplacingOccurrencesOfString:@"+" withString:@""];
hmutStr = [tempString stringByReplacingOccurrencesOfString:@"-" withString:@""];
如果还有其他的字符就一次写入代码,进行过滤,比较繁琐,得写很多无用的代码,效率也不高!
方法二:
先将字符串按非法字符串集进行裁断,最后再拼接起来,代码看起来很直观,直接了断
具体代码如下:
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@"[]{}(#%-*+=_)\\|~(<>$%^&*)_+ "];
NSString * hmutStr = [[mutStr componentsSeparatedByCharactersInSet: doNotWant]componentsJoinedByString: @""];
NSLog(@"humStr is %@",hmutStr);
return hmutStr;
在doNotWant这个字符集里想写几个就写几个,很方便,一个方法就搞定了,这样的话,字符串直接的传输,就很方便了!
分享一个公用方法:字典转json字符串,并直接过滤掉里面的非法字符
#pragma mark 字典转json
- (NSString*)dictionaryToJson:(NSDictionary *)dic
{
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString;
if (!jsonData) {
NSLog(@"%@",error);
}else{
jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
}
NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
// NSRange range = {0,jsonString.length};
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@"[]{}(#%-*+=_)\\|~(<>$%^&*)_+ "];
NSString * hmutStr = [[mutStr componentsSeparatedByCharactersInSet: doNotWant]componentsJoinedByString: @""];
NSLog(@"humStr is %@",hmutStr);
return hmutStr;
}
当然方法有很多种,如果大家有什么好的方法,还希望大家不吝指教!
json转化为字典:具体代码如下:
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
if (jsonString == nil) {
return nil;
}
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *err;
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers
error:&err];
if(err)
{
NSLog(@"json解析失败:%@",err);
return nil;
}
return dic;
}
这个方法,我们在和后台调接口的时候,用的最多,这里只做记录用!