我有一个格式为
的输入字符串在这里,我应该首先根据逗号分隔符分隔字符串,这会给我一个单独的字符串,如
“Jerry Lane”(尖括号)jerry.lane@gmail.com(括号内关闭)
然后我需要在<>之间保存提取字符串括号,基本上是字符串“jerry.lane@gmail.com”。我使用以下代码,但它给了我以下错误:
由于未捕获的异常'NSRangeException'而终止应用程序,原因:' - [__ NSCFConstantString substringWithRange:]:范围或索引越界'
-(NSArray *)parseString:(NSString *)string
{
if(string)
{
NSArray *myArray = [string componentsSeparatedByString:@","];
for(NSMutableString *myString in myArray)
{
NSRange start,end;
start = [myString rangeOfString:@"<"];
end = [myString rangeOfString:@">"];
if(start.location != NSNotFound && end.location != NSNotFound)
{
NSString *emailAddress = [myString substringWithRange:NSMakeRange(start.location,end.location)];
NSString *name = [myString substringToIndex:start.location];
NSDictionary *myDictionary = [[NSDictionary alloc] init];
[myDictionary setValue:emailAddress forKey:@"Dhruvil Vyas"];
[testArray addObject:myDictionary];
}
}
}
return testArray;
}
答案 0 :(得分:4)
答案 1 :(得分:1)
borrrden的回答是正确的。这是另一种方法。
-(NSArray *)parseString:(NSString *)string
{
if(string)
{
NSArray *myArray = [string componentsSeparatedByString:@","];
for(NSMutableString *myString in myArray)
{
NSArray *tempNameArray = [myString componentsSeparatedByString:@"<"];
NSString *email = [tempNameArray objectAtIndex:1];
NSArray *tempMailArray = [email componentsSeparatedByString:@">"];
NSString *emailAddress = [tempMailArray objectAtIndex:0];
NSString *name = [tempNameArray objectAtIndex:0];
NSDictionary *myDictionary = [[NSDictionary alloc] init];
[myDictionary setValue:emailAddress forKey:@"Dhruvil Vyas"];
[testArray addObject:myDictionary];
}
}
return testArray;
}