Created
November 30, 2011 22:21
-
-
Save mdippery/1411362 to your computer and use it in GitHub Desktop.
Ruby's string slicing functions, now in delicious Objective-C flavor!
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 (Slicing) | |
- (unichar)characterAt:(NSInteger)index; | |
- (NSString *)stringBySlicingFromIndex:(NSInteger)start length:(NSUInteger)length; | |
- (NSString *)stringBySlicingFromIndex:(NSInteger)start toIndex:(NSInteger)end; | |
@end | |
@implementation NSString (Slicing) | |
- (unichar)characterAt:(NSInteger)index | |
{ | |
if (index < 0) index = [self length] - -index; | |
return [self characterAtIndex:index]; | |
} | |
- (NSString *)stringBySlicingFromIndex:(NSInteger)start length:(NSUInteger)length | |
{ | |
if (start < 0) start = [self length] - -start; | |
NSRange range = NSMakeRange(start, length); | |
return [self substringWithRange:range]; | |
} | |
- (NSString *)stringBySlicingFromIndex:(NSInteger)start toIndex:(NSInteger)end | |
{ | |
if (start < 0) start = [self length] - -start; | |
if (end < 0) end = [self length] - -end; | |
if (start >= [self length] || end >= [self length]) return nil; | |
if (start > end) return @""; | |
NSUInteger length = end + 1 - start; | |
NSRange range = NSMakeRange(start, length); | |
return [self substringWithRange:range]; | |
} | |
@end | |
int main(int argc, char **argv) | |
{ | |
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; | |
NSString *s = @"hello there"; | |
NSString *x; | |
unichar ch = [s characterAt:-1]; | |
NSLog(@"%C", ch); | |
x = [s stringBySlicingFromIndex:1 length:3]; | |
NSLog(@"%@", x); | |
x = [s stringBySlicingFromIndex:1 toIndex:3]; | |
NSLog(@"%@", x); | |
x = [s stringBySlicingFromIndex:-3 length:2]; | |
NSLog(@"%@", x); | |
x = [s stringBySlicingFromIndex:-4 toIndex:-2]; | |
NSLog(@"%@", x); | |
x = [s stringBySlicingFromIndex:12 toIndex:-1]; | |
NSLog(@"%@", x); | |
x = [s stringBySlicingFromIndex:-2 toIndex:-4]; | |
NSLog(@"%@", x); | |
[pool release]; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment