0%

OC根据分隔符分隔字符串

同学前几天面试面到了这个题,毕竟闷了半天才闷出来.记录一下省的忘了…

NSString+Category.h文件

#import <Foundation/Foundation.h>

@interface NSString (Category)

/**
 * 根据分隔符,分隔字符串
 *
 * @param symbol 分隔符
 *
 * @return 由被分隔完的字串组成的数组
 */
- (NSArray *)splitStringWithSymbol:(NSString *)symbol;

@end

NSString+Category.m文件

#import "NSString+Category.h"

@implementation NSString (Category)

- (NSArray *)splitStringWithSymbol:(NSString *)symbol {
    
    if (!self || [self isEqualToString:@""] || !symbol || [self isEqualToString:@""]) {
        NSException *e = [NSException exceptionWithName:@"NullPointerException" reason:@"self and symbol can't be nil or @\"\"" userInfo:nil];
        @throw e;
    }
    
    NSMutableArray *mutableArr = [NSMutableArray new];
    NSInteger length = symbol.length;
    NSString *tempStr = nil;
    
    for (int startIndex = 0, endIndex = 0; endIndex <= self.length - length; endIndex++) {
        
        tempStr = [self substringWithRange:NSMakeRange(endIndex, length)];
        if ([tempStr isEqualToString:symbol]) {
            NSString *splitedString = [self substringWithRange:NSMakeRange(startIndex, endIndex - startIndex)];
            if (splitedString && ![splitedString isEqualToString:@""]) {
                [mutableArr addObject:splitedString];
            }
            startIndex = endIndex + (int)length;
        } else if (endIndex == self.length - length){
            NSString *splitedString = [self substringWithRange:NSMakeRange(startIndex, endIndex - startIndex + length)];
            if (splitedString && ![splitedString isEqualToString:@""]) {
                [mutableArr addObject:splitedString];
            }
        }
        
    }
    
    return [mutableArr copy];
}
@end

以上代码有个问题,当字符串是,asdf,,123,分隔字符是,,分隔结果是(asdf,123),而不是(asdf,(前面一个是数组的逗号),123).
试了一下官方的componentsSeparatedByString方法,相同的字符串跟分隔符,输出结果是("",asdf,"",123),连是否是@""都没判断.Java当中实验的结果跟OC结果相同.官方方法都这样,我想我是想多了.

–EOF–