🍎
文字列から指定した文字のみを取り出すNSMutableString拡張メソッド
[string filterString:hoge]
の形で、string文字列からhoge指定文字のみを取り出し、結果をstringにセットし直します。
#例
文字列 | 引数 | 結果 |
---|---|---|
(03)5321-1111 | 0123456789 | 0353211111 |
AaBbCcDd | ABcd | ABcd |
あのイーハトーヴォのすきとおった風 | あいうえおかきくけこ | あきお |
égalité | abcdefghijklmnop | gali |
NSMutableString+Filter.h
#import <Foundation/Foundation.h>
@interface NSMutableString (Filter)
- (void)filterString:(NSString *)character;
@end
NSMutableString+Filter.m
#import "NSMutableString+Filter.h"
@implementation NSMutableString (Filter)
- (void)filterString:(NSString *)character
{
if ([self length] == 0)
return;
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];
}
[self setString:result];
}
@end
History
- 20130405 ver1.0.1 zero lengthに対応
- 20130403 ver1.0
Discussion