Last active
January 3, 2016 15:49
-
-
Save brennanMKE/8485722 to your computer and use it in GitHub Desktop.
A string problem for collating 2 strings together. Strings "abcdef" and "123456" become "a1b2c3d4e5f6."
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 "NSString+Collate.h" | |
int main(int argc, const char * argv[]) | |
{ | |
@autoreleasepool { | |
NSArray *collection = @[ | |
@[@"a", @"1"], | |
@[@"ab", @"12"], | |
@[@"abcdef", @"123456"], | |
@[@"ab", @"1234"], | |
@[@"abcd", @"12"], | |
@[@"abc", @"abc"], | |
@[@"123", @"123"] | |
]; | |
NSUInteger i = 1; | |
for (NSArray *strings in collection) { | |
NSString *str1 = strings[0]; | |
NSString *str2 = strings[1]; | |
NSLog(@"%lu: %@", i, [str1 collateWithOtherString:str2]); | |
i++; | |
} | |
} | |
return 0; | |
} |
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
@interface NSString (Collate) | |
- (NSString *)collateWithOtherString:(NSString *)otherString; | |
@end |
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
@implementation NSString (Collate) | |
- (NSString *)collateWithOtherString:(NSString *)otherString { | |
return [self collateString1:self string2:otherString]; | |
} | |
- (NSString *)collateString1:(NSString *)str1 string2:(NSString *)str2 { | |
NSMutableString *result = [@"" mutableCopy]; | |
for (NSUInteger index=0; (index<str1.length || index<str2.length); index++) { | |
if (index < str1.length) { | |
[result appendString:[str1 substringWithRange:NSMakeRange(index, 1)]]; | |
} | |
if (index < str2.length) { | |
[result appendString:[str2 substringWithRange:NSMakeRange(index, 1)]]; | |
} | |
} | |
return result; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment