Skip to content

Instantly share code, notes, and snippets.

@ryanmaxwell ryanmaxwell/gist:4999567
Last active Dec 14, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.