NSString
任意の文字列の n 番目の出現を見つけることを処理するカテゴリを作成できます。これは ARC の例です。
//NSString+MyExtension.h
@interface NSString(MyExtension)
-(NSString*)substringToNthOccurrence:(NSUInteger)nth
ofString:(NSString*)string;
-(NSString*)substringToNthOccurrence:(NSUInteger)nth
ofString:(NSString*)string
options:(NSStringCompareOptions)options;
@end
@implementation NSString(MyExtension)
-(NSString*)substringToNthOccurrence:(NSUInteger)nth
ofString:(NSString*)string
{
return [self substringToNthOccurrence:nth ofString:string options:0];
}
-(NSString*)substringToNthOccurrence:(NSUInteger)nth
ofString:(NSString*)string
options:(NSStringCompareOptions)options
{
NSUInteger location = 0,
strlength = [string length],
mylength = [self length];
NSRange range = NSMakeRange(location, mylength);
while(nth--)
{
location = [self rangeOfString:string
options:options
range:range].location;
if(location == NSNotFound || (location + strlength) > mylength)
{
return [self copy]; //nth occurrence not found
}
if(nth == 0) strlength = 0; //This prevents the last occurence from being included
range = NSMakeRange(location + strlength, mylength - strlength - location);
}
return [self substringToIndex:location];
}
@end
//main.m
#import "NSString+MyExtension.h"
int main(int argc, char *argv[])
{
@autoreleasepool {
NSString *output = [@"title, price, Camry, $19798, active" substringToNthOccurrence:2 ofString:@","];
NSLog(@"%@", output);
}
}
*変更可能なバージョンを実装するための演習として残します。