我正在尝试获取标题的第一个字母/数字,这是对象的NSString属性。该属性有时可能是nil或= @“”,所以我需要对此进行补偿。如果 标题以我需要返回@“#”的数字开头。如果它像“杯子”一样开始,我需要返回“C”而不管“The”。如果它是空的,我需要返回U代表未知。
我创建了以下脚本,但在搜索1000个标题时速度非常慢。有时我收到-[__NSCFString substringToIndex:]: Index 1 out of bounds; string length 0
。我认为这与空字符串有关?还有其他任何方法,比如正则表达式或我可以用来加速查询的东西吗?
- (NSString *)firstLetterInTitle{
NSString *newString = [self.title uppercaseString];
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
if([newString length] >= 1){
if([f numberFromString:[newString substringToIndex:1]] != nil){
//All Numbers
_firstLetterInTitle = @"#";
return _firstLetterInTitle;
}
//" Hello"
if([newString length] >= 2){
if([[newString substringToIndex:1] isEqualToString:@" "]){
newString = [newString stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]];
//Returns "Hello"
}
}
if([newString length] >= 5){
if([[newString substringToIndex:4] isEqualToString:@"THE "]){
newString = [newString substringFromIndex:4];
}
}
}else{
_firstLetterInTitle = @"U";
return _firstLetterInTitle;
}
newString = [[newString componentsSeparatedByCharactersInSet:[[NSCharacterSet letterCharacterSet] invertedSet]] componentsJoinedByString:@""];
if([newString length] >= 1){
_firstLetterInTitle = [newString substringToIndex:1];
}else{
_firstLetterInTitle = @"U";
}
return _firstLetterInTitle;
}
答案 0 :(得分:4)
这应该更快一些
- (NSString *)firstLetterInTitle
{
if (!self.title || ([self.title isEqualToString:@""])) {
return @"U";
}
if ([[NSCharacterSet decimalDigitCharacterSet] characterIsMember:[self.title characterAtIndex:0]]) {
return @"#";
}
NSString *newString = [self.title uppercaseString];
if (([newString hasPrefix:@"THE "]) && ([newString length > 4)) {
newString = [newString substringFromIndex:4];
}
return [newString substringToIndex:1];
}