🍎
文字列から指定した文字のみを取り出し生成するNSString拡張メソッド
NSString *after = [before filteredString:hoge]
の形で、before文字列からhoge指定文字のみを取り出し、NSStringを生成します。
#例
文字列 | 引数 | 結果 |
---|---|---|
(03)5321-1111 | 0123456789 | 0353211111 |
AaBbCcDd | ABcd | ABcd |
あのイーハトーヴォのすきとおった風 | あいうえおかきくけこ | あきお |
égalité | abcdefghijklmnop | gali |
NSString+Filter.h
#import <Foundation/Foundation.h>
@interface NSString (Filter)
- (NSString *)filteredString:(NSString *)character;
@end
NSString+Filter.m
#import "NSString+Filter.h"
@implementation NSString (Filter)
- (NSString *)filteredString:(NSString *)character
{
if ([self length] == 0)
return [NSString string];
NSCharacterSet* charSet;
NSString* scanned;
NSMutableString *exclude = [[NSMutableString alloc] init];
NSMutableString *result = [[NSMutableString alloc] init];
NSScanner* scanner;
//Extract the character to exclude.
charSet = [NSCharacterSet characterSetWithCharactersInString:character];
scanner = [NSScanner scannerWithString:self];
while(![scanner isAtEnd]) {
if([scanner scanUpToCharactersFromSet:charSet intoString:&scanned]) {
[exclude appendString:scanned];
}
[scanner scanCharactersFromSet:charSet intoString:nil];
}
//Filter unwanted characters from a string.
charSet = [NSCharacterSet characterSetWithCharactersInString:exclude];
scanner = [NSScanner scannerWithString:self];
while(![scanner isAtEnd]) {
if([scanner scanUpToCharactersFromSet:charSet intoString:&scanned]) {
[result appendString:scanned];
}
[scanner scanCharactersFromSet:charSet intoString:nil];
}
return [NSString stringWithString:result];
}
@end
History
- 20130405 ver1.0.1 zero lengthに対応
- 20130404 ver1.0
Discussion