在iOS的实际开发中,常会出现需要去除空格的情况,总结有三种情况:
- 去除字符串首尾连续字符(如空格);
- 去除字符串首部连续字符(如空格);
- 去除字符串尾部连续字符(如空格);
去除字符串首尾连续字符(如空格)
NSString *a = @" a sdf ";
[a stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
去除字符串首部连续字符(如空格);
NSString *a = @" a sdf ";
NSString *leftResult = [a stringByTrimmingLeftCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
#import "NSString+util.h"
@implementation NSString (util)
- (NSString *)stringByTrimmingLeftCharactersInSet:(NSCharacterSet *)characterSet {
NSUInteger location = 0;
NSUInteger length = [self length];
unichar charBuffer[length];
[self getCharacters:charBuffer range:NSMakeRange(0, length)];
for (NSInteger i = 0; i < length; i++) {
if (![characterSet characterIsMember:charBuffer[i]]) {
location = i;
break;
}
}
return [self substringWithRange:NSMakeRange(location, length - location)];
}
去除字符串尾部连续字符(如空格);
NSString *a = @" a sdf ";
NSString *rightResult = [a stringByTrimmingRightCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
- (NSString *)stringByTrimmingRightCharactersInSet:(NSCharacterSet *)characterSet {
NSUInteger length = [self length];
unichar charBuffer[length];
[self getCharacters:charBuffer range:NSMakeRange(0, length)];
NSUInteger subLength = 0;
for (NSInteger i = length; i > 0; i--) {
if (![characterSet characterIsMember:charBuffer[i - 1]]) {
subLength = i;
break;
}
}
return [self substringWithRange:NSMakeRange(0, subLength)];
}