1. 程式人生 > >如何去掉String的前後空格或某些字元

如何去掉String的前後空格或某些字元

#import <Foundation/Foundation.h>

@interface NSString (TrimmingAdditions)

/**
 *  去掉字串左邊的特定字元
 *
 *  @param characterSet 需要去除的特定字符集
 *
 *  @return 去除後的字串
 */
- (NSString *)stringByTrimmingLeftCharactersInSet:(NSCharacterSet *)characterSet;

/**
 *  去掉字串右邊的特定字元
 *
 *  @param characterSet 需要去除的特定字符集
 *
 *  @return 去除後的字串
 */
- (NSString *)stringByTrimmingRightCharactersInSet:(NSCharacterSet *)characterSet;

@end
@implementation NSString (TrimmingAdditions)

- (NSString *)stringByTrimmingLeftCharactersInSet:(NSCharacterSet *)characterSet {
    NSUInteger location = 0;
    NSUInteger length = [self length];
    unichar charBuffer[length];
    //This method is unsafe because it could potentially cause buffer overruns.
    //[self getCharacters:charBuffer];
    [self getCharacters:charBuffer range:NSMakeRange(location, length)];
    for (location = 0; location < length; location++) {
        // charBuffer[i] 是 字元對應的ASCII值
        //DLog(@"charBuffer = %hu", charBuffer[location]);
        if (![characterSet characterIsMember:charBuffer[location]]) {
            break;
        }
    }
    return [self substringWithRange:NSMakeRange(location, length - location)];
}

- (NSString *)stringByTrimmingRightCharactersInSet:(NSCharacterSet *)characterSet {
    NSUInteger location = 0;
    NSUInteger length = [self length];
    unichar charBuffer[length];
    //[self getCharacters:charBuffer];
    [self getCharacters:charBuffer range:NSMakeRange(location, length)];
    for (length = [self length]; length > 0; length--) {
        if (![characterSet characterIsMember:charBuffer[length - 1]]) {
            break ;
        }
    }
    return [self substringWithRange:NSMakeRange(location, length - location)];
}

@end