iOS高质量博客

iOS如何过滤掉文本中特殊字符

2016-11-11  本文已影响401人  彗星来的那一夜

如果需要去掉字符串中特殊的字符可以调用NSString的
stringByTrimmingCharactersInSet的方法:

- (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set;

以下是例子:

①去掉两端的空格:

NSString *str = @"  #####! 2 Z c c ";

NSString *s = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
//该方法是去掉两端的空格或者可以用
 NSString *s =  [s stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@" "]];

NSLog(@"he%@hehe",s);  
//输出结果为:he#####! 2 Z c chehe

②去掉指定符号:

NSString *b = [s stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"#!"]];
//该方法是去掉指定符号

NSLog(@"hl%@",b);
//输出结果为:hl 2 Z c c

③去掉字符串中所有的空格符

NSString *string =  @"    Just    play  a    test    .  ";

NSCharacterSet *whitespaces = [NSCharacterSet whitespaceCharacterSet];

NSPredicate *noEmptyStrings = [NSPredicate predicateWithFormat:@"SELF != ''"];

NSArray *parts = [string componentsSeparatedByCharactersInSet:whitespaces];
//在空格处将字符串分割成一个 NSArray

NSArray *filteredArray = [parts filteredArrayUsingPredicate:noEmptyStrings];
//去除空串

NSString *jointStr  = @"" ;

string = [filteredArray componentsJoinedByString:jointStr];
上一篇下一篇

猜你喜欢

热点阅读