要反转字符串,可以直接反序遍历,也可以同时从两侧遍历并交换字符。这里我们用快一点的方法,同时从两侧遍历,图解如下:
字符串反转
OC原汁原味的示例代码:
@implementation NSString (Reverse)
-(NSString *)reverse {
NSMutableString *temp = [self mutableCopy];
NSUInteger left = 0;
NSUInteger right = temp.length - 1;
while (left < right) {
NSString *leftStr = [temp substringWithRange:NSMakeRange(left, 1)];
NSString *rightStr = [temp substringWithRange:NSMakeRange(right, 1)];
[temp replaceCharactersInRange:NSMakeRange(left, 1) withString:rightStr];
[temp replaceCharactersInRange:NSMakeRange(right, 1) withString:leftStr];
left ++;
right --;
}
return [temp copy];
}
@end
网友评论