同學(xué)前幾天面試面到了這個(gè)題,畢竟悶了半天才悶出來(lái).記錄一下省的忘了...
==NSString+Category.h文件==
#import <Foundation/Foundation.h>
@interface NSString (Category)
/**
* 根據(jù)分隔符,分隔字符串
*
* @param symbol 分隔符
*
* @return 由被分隔完的字串組成的數(shù)組
*/
- (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
以上代碼有個(gè)問(wèn)題,當(dāng)字符串是,asdf,,123
,分隔字符是,
,分隔結(jié)果是(asdf,123)
,而不是(asdf,(前面一個(gè)是數(shù)組的逗號(hào)),123)
.
試了一下官方的componentsSeparatedByString
方法,相同的字符串跟分隔符,輸出結(jié)果是("",asdf,"",123)
,連是否是@""
都沒(méi)判斷.Java當(dāng)中實(shí)驗(yàn)的結(jié)果跟OC結(jié)果相同.官方方法都這樣,我想我是想多了.
本文原地址:OC根據(jù)分隔符分隔字符串
--EOF--