Skip to content

Instantly share code, notes, and snippets.

@software-mariodiana
Created November 23, 2020 23:34
Show Gist options
  • Save software-mariodiana/edeb11b1805c7ea0dfcece03ffe150dd to your computer and use it in GitHub Desktop.
Save software-mariodiana/edeb11b1805c7ea0dfcece03ffe150dd to your computer and use it in GitHub Desktop.
Split an NSString into an NSArray of its characters.
#import <Foundation/Foundation.h>
int main(int argc, char *argv[]) {
@autoreleasepool {
NSString* s = @"antidisestablishmentarianism";
unichar* buffer = (unichar *)malloc(sizeof(unichar) * [s length]);
[s getCharacters:buffer range:NSMakeRange(0, [s length])];
NSMutableArray* temp = [NSMutableArray arrayWithCapacity:[s length]];
for (int i = 0; i < [s length]; i++) {
[temp addObject:[NSString stringWithFormat:@"%C", buffer[i]]];
}
free(buffer);
NSArray* characters = [NSArray arrayWithArray:temp];
NSLog(@"%@", characters);
}
return 0;
}
@software-mariodiana
Copy link
Author

@interface NSString (MDXComponents)
- (NSArray *)mdx_components;
@end

@implementation NSString (MDXComponents)

- (NSArray *)mdx_components
{
    unichar* buffer = (unichar *)malloc(sizeof(unichar) * [self length]);
    [self getCharacters:buffer range:NSMakeRange(0, [self length])];
    
    NSMutableArray* temp = [NSMutableArray arrayWithCapacity:[self length]];
    
    for (int i = 0; i < [self length]; i++) {
        [temp addObject:[NSString stringWithFormat:@"%C", buffer[i]]];
    }
    
    free(buffer);
    
    return [NSArray arrayWithArray:temp];
}

@end

@software-mariodiana
Copy link
Author

@interface NSString (MDXString)
- (NSArray *)allCharacters;
@end

@implementation NSString (MDXString)

- (NSArray *)allCharacters
{
    CFStringRef ref = (__bridge CFStringRef)self;
    NSMutableArray* characters = [NSMutableArray arrayWithCapacity:[self length]];
    
    for (int i = 0; i < [self length]; i++) {
        [characters addObject:[NSString stringWithFormat:@"%C", CFStringGetCharacterAtIndex(ref, i)]];
    }
    
    return [NSArray arrayWithArray:characters];
}

@end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment