Reputation: 5117
If there is an NSString like "com.mycompany.purchase1" How to get only purchase1.
NSString *mainString = @"com.mycompany.purchase1";
-(NSString*)getLastComponent : (NSString*) mainString
{
NSString *string;
//Implementation
return string;//It should return only "purchase1"
}
I tried using lastPathComponent,pathExtension and also i can't use substringToIndex since the string may be of varying length.
Upvotes: 1
Views: 170
Reputation: 12787
-(NSString*)getLastComponent : (NSString*) mainString
{
NSString *string1;
NSArray *arr=[mainString componentsSeparatedByString:@"."];
string1=[arr objectAtIndex:([arr count]-1)];
return string;
}
use above code.
Upvotes: 0
Reputation: 2234
Don't want donkim's answer as he is correct. Just showing the implementation I would use
-(NSString*)lastComponentOfString:(NSString*)string separatedByString:(NSString*)separator
{
return [[string componentsSeparatedByString:separator] lastObject];
}
Use
NSString *string = @"com.mycompany.purchase1";
[... lastComponentOfString:string separatedByString:@"."];
Upvotes: 7
Reputation: 13137
You could use the - (NSArray *)componentsSeparatedByString:(NSString *)separator
method in NSString
. Check to see that NSArray
has a count greater than 0 and the last component of it ([array objectAtIndex:[array count] - 1]
) will be what you want.
Upvotes: 2