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 .结束