Created
August 21, 2015 07:15
-
-
Save elliotchance/b2e92ee4127400509c85 to your computer and use it in GitHub Desktop.
NSString+Split
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
@interface NSString (Split) | |
- (NSArray *)componentsSeparatedByString:(NSString *)separator | |
limit:(NSUInteger)limit; | |
@end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import "NSString+Split.h" | |
@implementation NSString (Split) | |
- (NSArray *)componentsSeparatedByString:(NSString *)separator | |
limit:(NSUInteger)limit | |
{ | |
if (limit == 0) { | |
return @[]; | |
} | |
NSArray *components = [self componentsSeparatedByString:separator]; | |
if ([components count] > limit) { | |
NSArray *a = [components subarrayWithRange:NSMakeRange(0, limit - 1)]; | |
NSArray *b = [components subarrayWithRange:NSMakeRange(limit - 1, [components count] - limit + 1)]; | |
components = [a arrayByAddingObject:[b componentsJoinedByString:separator]]; | |
} | |
return components; | |
} | |
@end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <XCTest/XCTest.h> | |
#define HC_SHORTHAND | |
#import <OCHamcrestExtensions/OCHamcrest.h> | |
#import "NSString+Split.h" | |
@interface NSStringSplitTest : XCTestCase | |
{ | |
} | |
@end | |
@implementation NSStringSplitTest | |
- (void)testComponentsReturnsAnArray | |
{ | |
assertThat([@"" componentsSeparatedByString:@"" limit:1], | |
instanceOf([NSArray class])); | |
} | |
- (void)testStringCannotBeSplit | |
{ | |
assertThat([@"foo" componentsSeparatedByString:@"bar" limit:1], | |
equalTo(@[@"foo"])); | |
} | |
- (void)testLimitIsZero | |
{ | |
assertThat([@"" componentsSeparatedByString:@"" limit:0], | |
equalTo(@[])); | |
} | |
- (void)testSplittingAStringLessThanTheLimit | |
{ | |
assertThat([@"a-b-c" componentsSeparatedByString:@"-" limit:10], | |
equalTo(@[@"a", @"b", @"c"])); | |
} | |
- (void)testLimitIsLessThanComponents | |
{ | |
assertThat([@"a-b-c-d" componentsSeparatedByString:@"-" limit:2], | |
equalTo(@[@"a", @"b-c-d"])); | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment