搜索
您的当前位置:首页正文

iOS 去除字符串中的特殊字符总结

来源:二三娱乐

如果需要去掉字符串中特殊的字符可以调用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(@"hl%@ehe",s);  输出结果为:hl#####! 2 Z c cehe

—去掉指定符号:

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];

NSLog(@"开始%@结束",string);//输出结果为:开始Justplayatest.结束

如果NSString *jointStr  = @" " ;

那么NSLog(@"开始%@结束",string);//输出结果为:开始Just play a test .结束

Top