Last active
July 20, 2018 03:57
-
-
Save unixzii/7e18afcea3bdb40e814d758bb0a1580e to your computer and use it in GitHub Desktop.
The right way to reverse a string
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> | |
void strrev(char *str) { | |
size_t start = 0; | |
size_t end = start + strlen(str) - 1; | |
while (start < end) { | |
char ch = str[start]; | |
str[start++] = str[end]; | |
str[end--] = ch; | |
} | |
} | |
void strrev2(char *str) { | |
size_t len = mbstowcs(NULL, str, 0); | |
wchar_t *wcs = (wchar_t *) calloc(len + 1, sizeof(wchar_t)); | |
mbstowcs(wcs, str, len + 1); | |
size_t start = 0; | |
size_t end = start + len - 1; | |
while (start < end) { | |
wchar_t wc = wcs[start]; | |
wcs[start++] = wcs[end]; | |
wcs[end--] = wc; | |
} | |
wcstombs(str, wcs, wcstombs(NULL, wcs, 0)); | |
free(wcs); | |
} | |
@implementation NSString (Reverse) | |
- (NSString *)my_stringByReversing { | |
NSUInteger length = [self lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; | |
char *str = (char *) calloc(1, length); | |
[self getBytes:str | |
maxLength:length | |
usedLength:nil | |
encoding:NSUTF8StringEncoding | |
options:0 | |
range:NSMakeRange(0, self.length) | |
remainingRange:nil]; | |
strrev2(str); | |
NSString *reversed = [NSString stringWithCString:str encoding:NSUTF8StringEncoding]; | |
free(str); | |
return reversed; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment