Objective-C 去掉NSString 前后中空格
NSString 中缺少类似 Java 中的 .trim() 方法。直接去掉字符串类型值前后的空格。需要使用如下方法。
1、去掉前后空格
NSString *cleanString = [dirtyString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
2、还有就是去除多于的空格,如下
NSString *theString = @" Hello this is a long string! "; NSCharacterSet *whitespaces = [NSCharacterSet whitespaceCharacterSet]; NSPredicate *noEmptyStrings = [NSPredicate predicateWithFormat:@"SELF != ''"]; NSArray *parts = [theString componentsSeparatedByCharactersInSet:whitespaces]; NSArray *filteredArray = [parts filteredArrayUsingPredicate:noEmptyStrings]; theString = [filteredArray componentsJoinedByString:@" "];