Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
//
// NSString+Hendrix.h
// Hendrix
//
// Created by Justin Palmer on 3/2/09.
// Copyright 2009 Alternateidea. All rights reserved.
//
@interface NSString (Hendrix)
- (NSString *)underscore;
- (NSString *)dasherize;
@end
//
// NSString+Hendrix.m
// Hendrix
//
// Created by Justin Palmer on 3/2/09.
// Copyright 2009 Alternateidea. All rights reserved.
//
#import "NSString+Hendrix.h"
@interface NSString (HendrixPrivateMethods)
- (NSString *)normalizeWith:(NSString *)delimiter;
@end
@implementation NSString (Hendrix)
- (NSString *)dasherize
{
return [self normalizeWith:@"-"];
}
- (NSString *)underscore
{
return [self normalizeWith:@"_"];
}
- (NSString *)normalizeWith:(NSString *)delimeter
{
NSString *lc = @"";
NSUInteger length = [self length];
NSCharacterSet *uppercaseSet = [NSCharacterSet uppercaseLetterCharacterSet];
NSCharacterSet *delimiterSet = [NSCharacterSet characterSetWithCharactersInString:@"_-"];
NSMutableString *out = [NSMutableString string];
for (NSUInteger i = 0; i < length; i++)
{
unichar uc = [self characterAtIndex:i];
if([uppercaseSet characterIsMember:uc])
{
unichar lcc = [self characterAtIndex:(i - 1)];
if([lc isEqualToString:delimeter] || [uppercaseSet characterIsMember:lcc] || i == 0)
{
[out appendFormat:@"%C", uc];
}
else
{
[out appendFormat:@"%@%C", delimeter, uc];
}
}
else if([delimiterSet characterIsMember:uc])
{
NSString *delStr = [NSString stringWithFormat:@"%C", uc];
if(![delStr isEqualToString:delimeter] || i == 0)
{
[out appendString:delimeter];
lc = delimeter;
continue;
}
else
{
[out appendFormat:@"%C", uc];
}
}
else
{
[out appendFormat:@"%C", uc];
}
lc = [NSString stringWithFormat:@"%C", uc];
}
return [out lowercaseString];
}
@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.