-1

我是 iphone 开发的菜鸟,我正在尝试从 NSString 值创建一个子字符串,该值总是会改变。基本上,我正在尝试对字符串的最后一部分进行子串化。该字符串的格式为“March 15 PM Metals Commentary: John Jones” 我想要字符串的姓氏部分 例如,“Jones”而不是“John Jones”。我尝试过的两种方法要么给我异常,要么不返回任何值。任何帮助是极大的赞赏。

我的代码

//This approach throw index out of bounds exception
NSString * storyLink2 = [[stories objectAtIndex: storyIndex] objectForKey: @"title"];
NSRange namestart = [storyLink2 rangeOfString:@" " options:NSBackwardsSearch];
NSString *name = [[[stories objectAtIndex: storyIndex] objectForKey: @"title"] substringWithRange:NSMakeRange(namestart.location +1, name.length - namestart.location+1)];

//This approach return nothing
NSString *name = [[stories objectAtIndex: storyIndex] objectForKey: @"title"];
NSArray *thingitems = [name componentsSeparatedByString:@" "];
name = [thingitems lastObject];

编辑

  NSString *name = [[stories objectAtIndex: storyIndex] objectForKey: @"title"];
NSLog(@"myname: %@", name);// <-- Showing  "March 15 PM Metals Commentary: John Jones"
NSArray *thingitems = [name componentsSeparatedByString:@":"]; ////<-- [__NSArrayM componentsSeparatedByString:]: unrecognized selector sent to instance 0x89741a0
NSArray *lastName=[thingitems componentsSeparatedByString:@" "];
name = [lastName lastObject];
NSLog(@"myname: %@", name);

日志

2013-03-17 01:30:39.738 GSCC[704:207] myname: March 15 PM Metals Commentary: Thomas Vitiello

2013-03-17 01:30:39.739 GSCC[704:207] -[__NSArrayM componentsSeparatedByString:]: unrecognized selector sent to instance 0x89741a0
2013-03-17 01:30:39.741 GSCC[704:207] Exception - -[__NSArrayM componentsSeparatedByString:]: unrecognized selector sent to instance 0x89741a0
4

3 回答 3

2

如果您的字符串是"March 15 PM Metals Commentary: John Jones"并且您总是希望在冒号“:”之后的最后一部分出现名称,那么:

NSString *str=@"March 15 PM Metals Commentary: John Jones";
//use storyLink2 in place of str
NSString *name=[str componentsSeparatedByString:@":"][1];

编辑:

如果你只想要姓氏:那么

NSString *str=@"March 15 PM Metals Commentary: John Jones";
//use storyLink2 in place of str
NSArray *fullname=[str componentsSeparatedByString:@" "];
NSArray *lastName=[fullname lastObject];
于 2013-03-17T05:11:09.387 回答
0

如果你只想要最后一句话string,试试吧[ [ string componentsSeparatedByCharactersInSet:[ NSCharacterSet whitespaceCharacterSet ] ] lastObject ]

于 2013-03-17T05:40:36.630 回答
0

我已经对此进行了测试,没有错误

NSString *string = @"March 15 PM Metals Commentary: John Jones";
NSString *lastName = [[string componentsSeparatedByString:@" "] lastObject];
NSLog(@"%@",lastName);

所以我觉得你的可能是这样的?

NSString *name = [[stories objectAtIndex: storyIndex] objectForKey: @"title"];
NSString *lastName=[[name componentsSeparatedByString:@" "] lastObject];
NSLog(@"myname: %@", lastName);
于 2013-03-17T05:49:47.717 回答