Last active
December 14, 2015 00:29
-
-
Save ryanmaxwell/4999567 to your computer and use it in GitHub Desktop.
NSString+GroupedDelimitedString Category
This file contains 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 (GroupedDelimitedString) | |
- (NSString *)stringByGroupingBySize:(NSInteger)groupSize withDelimiter:(NSString *)delimiter; | |
@end |
This file contains 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+GroupedDelimitedString.h" | |
@implementation NSString (GroupedDelimitedString) | |
- (NSString *)stringByGroupingBySize:(NSInteger)groupSize withDelimiter:(NSString *)delimiter { | |
NSString *stringToGroup = [self stringByReplacingOccurrencesOfString:delimiter withString:@""]; | |
if (stringToGroup.length > groupSize) { | |
NSMutableString *paddedString = [NSMutableString string]; | |
for (NSInteger index = 0; index < stringToGroup.length; index++) { | |
if (index % groupSize == 0){ | |
if (index + groupSize < stringToGroup.length) { | |
[paddedString appendFormat:@"%@%@", [stringToGroup substringWithRange:NSMakeRange(index, groupSize)], delimiter]; | |
} else { | |
/* final group */ | |
NSInteger finalLength = stringToGroup.length - index; | |
[paddedString appendString:[stringToGroup substringWithRange:NSMakeRange(index, finalLength)]]; | |
} | |
} | |
} | |
return paddedString; | |
} else { | |
return self; | |
} | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment