Skip to content

Instantly share code, notes, and snippets.

@ryanmaxwell
Last active December 14, 2015 00:29
Show Gist options
  • Save ryanmaxwell/4999567 to your computer and use it in GitHub Desktop.
Save ryanmaxwell/4999567 to your computer and use it in GitHub Desktop.
NSString+GroupedDelimitedString Category
#import <Foundation/Foundation.h>
@interface NSString (GroupedDelimitedString)
- (NSString *)stringByGroupingBySize:(NSInteger)groupSize withDelimiter:(NSString *)delimiter;
@end
#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