Objective-C分割字符串,分隔符是最后一个字符

时间:2015-09-03 18:39:37

标签: objective-c

我这里有这段代码:

NSArray *elements = [[[self.tableData objectAtIndex:indexPath.row] objectForKey:@"Name"] componentsSeparatedByString:@"\\"];

但这会创建多个对象,因为我的字符串看起来像Thiss \是\ a \ test,我想分割我的字符串或者只是在最后\\个字符后得到字符串的最后一部分。有可能这样做吗?

2 个答案:

答案 0 :(得分:3)

NSArray *elements = [[[[self.tableData objectAtIndex:indexPath.row] objectForKey:@"Name"] componentsSeparatedByString:@"\\"] lastObject];

应该适合你。

答案 1 :(得分:1)

NSString* wholeString = [[self.tableData objectAtIndex:indexPath.row] objectForKey:@"Name"];
NSArray* components = [wholeString componentsSeparatedByString:@"\\"];
NSString* lastPart = [components lastObject];
NSString* allExceptLast = [wholeString stringByReplacingOccurancesOfString:lastPart withString:@""];
allExceptLast = [allExceptLast stringByReplacingOccurancesOfString:@"\\" withString:@""];