我是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);
LOG
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
答案 0 :(得分: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];
答案 1 :(得分:0)
如果您只想要string
中的最后一个字,请尝试[ [ string componentsSeparatedByCharactersInSet:[ NSCharacterSet whitespaceCharacterSet ] ] lastObject ]
。
答案 2 :(得分: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);