iOS 去除空格

前后空格

NSString *cleanString = [dirtyString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; 

多余空格

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:@" "];  

你可能感兴趣的:(iOS 去除空格)