Skip to content

Commit

Permalink
NSString.split(@"") works
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
mxcl committed Mar 9, 2014
1 parent 9c795fd commit c17b416
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 1 deletion.
9 changes: 8 additions & 1 deletion NSString+YOLO.m
Original file line number Diff line number Diff line change
Expand Up @@ -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];
};
}

Expand Down
2 changes: 2 additions & 0 deletions README.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
```

Expand Down
4 changes: 4 additions & 0 deletions tests
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit c17b416

Please sign in to comment.