去除字符串左右两边的空白是比较通用的代码逻辑:
@interface NSString (Strip)
- (NSString *)wbt_trimmedString;
- (NSString *)wbt_leftTrimmedString;
- (NSString *)wbt_rightTrimmedString;
@end
@implementation NSString (Strip)
/* Returns a new string made by removing from start of the receiver whitespace and newline characters */
- (NSString *)wbt_leftTrimmedString
{
NSRange range = [self rangeOfCharacterFromSet:[NSCharacterSet whitespaceAndNewlineCharacterSet].invertedSet];
return [self substringFromIndex:range.location];
}
/* Returns a new string made by removing from end of the receiver whitespace and newline characters */
- (NSString *)wbt_rightTrimmedString
{
NSRange range = [self rangeOfCharacterFromSet:[NSCharacterSet whitespaceAndNewlineCharacterSet].invertedSet options:NSBackwardsSearch];
return [self substringToIndex:range.location];
}
/* Returns a new string made by removing from both ends of the receiver whitespace and newline characters */
- (NSString *)wbt_trimmedString
{
return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
@end
网友评论