From c17b41626b0963eeac322de3160f10fdc12567f0 Mon Sep 17 00:00:00 2001 From: Max Howell Date: Sat, 8 Mar 2014 19:42:35 -0600 Subject: [PATCH] NSString.split(@"") works It is logical that splitting by nothing will split by the smallest possible unit, ie. nothing, so all characters are split out into an array. Though, no other framework does this. It's often something I've expected and sometimes: needed. --- NSString+YOLO.m | 9 ++++++++- README.markdown | 2 ++ tests | 4 ++++ 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/NSString+YOLO.m b/NSString+YOLO.m index 3b1d107..8dd15b5 100644 --- a/NSString+YOLO.m +++ b/NSString+YOLO.m @@ -5,7 +5,14 @@ @implementation NSString (YOLO) - (NSArray *(^)(NSString *))split { return ^NSArray *(NSString *separator){ - return [self componentsSeparatedByString:separator]; + if (separator.length == 0) { + const NSUInteger N = self.length; + id chars[N]; + for (NSUInteger x = 0; x < N; ++x) + chars[x] = [self substringWithRange:NSMakeRange(x, 1)]; + return [NSArray arrayWithObjects:chars count:N]; + } else + return [self componentsSeparatedByString:separator]; }; } diff --git a/README.markdown b/README.markdown index 9b6aa2b..bfe1d3a 100644 --- a/README.markdown +++ b/README.markdown @@ -546,7 +546,9 @@ id rv = @1.upTo(6); ###NSString.split() ```objc id rv = @"1,2,3,4,5,6".split(@","); +// rv => @[@"1", @"2", @"3", @"4", @"5", @"6"] +id rv = @"123456".split(@""); // rv => @[@"1", @"2", @"3", @"4", @"5", @"6"] ``` diff --git a/tests b/tests index ed3142e..2f886d8 100755 --- a/tests +++ b/tests @@ -281,6 +281,10 @@ int main() { id aa = @"1,2,3,4".split(@","); id bb = @[@"1", @"2", @"3", @"4"]; XCTAssertEqualObjects(aa, bb); + + aa = @"1234".split(@""); + bb = @[@"1", @"2", @"3", @"4"]; + XCTAssertEqualObjects(aa, bb); } - (NSArray *)array:(NSUInteger)count {