NSString *str = nil;
// 去掉首尾空格和换行符
str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
// 去掉所有空格和换行符
str = [str stringByReplacingOccurrencesOfString:@"\r" withString:@""];
str = [str stringByReplacingOccurrencesOfString:@"\n" withString:@""];
如果要单独过滤左边或者右边的内容就需要自己来实现了。
可以在NSString的类目(Category)中提供如下两个方法:
// 过滤左边指定的内容
- (NSString *)stringByTrimmingLeftCharactersInSet:(NSCharacterSet *)characterSet {
NSUInteger location = 0;
NSUInteger length = [self length];
unichar charBuffer[length];
[self getCharacters:charBuffer];
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-value"
for (location; location < length; location++) {
if (![characterSet characterIsMember:charBuffer[location]]) {
break;
}
}
#pragma clang diagnostic pop
return [self substringWithRange:NSMakeRange(location, length - location)];
}
// 过滤右边指定的内容
- (NSString *)stringByTrimmingRightCharactersInSet:(NSCharacterSet *)characterSet {
NSUInteger location = 0;
NSUInteger length = [self length];
unichar charBuffer[length];
[self getCharacters:charBuffer];
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-value"
for (length; length > 0; length--) {
if (![characterSet characterIsMember:charBuffer[length - 1]]) {
break;
}
}
#pragma clang diagnostic pop
return [self substringWithRange:NSMakeRange(location, length - location)];
}
使用stringByTrimmingLeftCharactersInSet:
去掉左边的空格:
NSString *str = @" Yancy🙂 ";
str = [str stringByTrimmingLeftCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSLog(@"%@", str);
使用stringByTrimmingRightCharactersInSet:
去掉右边的"0":
NSString *str = @"0.012300";
str = [str stringByTrimmingRightCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"0"]];
NSLog(@"%@", str); // 结果是0.0123