Objective-C:字符串的反转Reverse

OC中字符串的反转方式可以用两种方式来处理:

第一种:从头到尾取出字符串的每一个字符,然后将其从尾到头添加到可变的字符串中,最后输出即可。

第二种:将OC内部的字符串转换为C语言中的字符串,然后动态分配一个数组,然后将字符串内容拷贝到数组中,进行首尾交换操作。共进行数组长度/2次操作。

 

方式一:OC版本

 1 -(NSMutableString*)Reverse
 2 {
 3     NSUInteger length = [self length];
 4     NSMutableArray *array = [NSMutableArray arrayWithCapacity:length];
 5     
 6     for(long i=length-1; i>=0; i--)
 7     {
 8         unichar c = [self characterAtIndex:i];
 9         [array addObject:[NSString stringWithFormat:@"%c",c]];
10     }
11     
12     
13     NSMutableString *str = [NSMutableString stringWithCapacity:length];
14     for(int i=0; i<=length-1; i++)
15     {
16         [str appendString:array[i]];
17     }
18     return str;
19  }@end

 

方式二:C语言版本

 1 @implementation NSString (Reverse)
 2 -(NSMutableString*)Reverse
 3 {
 4     const char *str = [self UTF8String];
 5     NSUInteger length = [self length];
 6     char *pReverse = (char*)malloc(length+1);//动态分配空间
 7     strcpy(pReverse, str);
 8     for(int i=0; i<length/2; i++)
 9     {
10         char c = pReverse[i];
11         pReverse[i] = pReverse[length-i-1];
12         pReverse[length-i-1] = c;
13     }
14     NSMutableString *pstr = [NSMutableString stringWithUTF8String:pReverse];
15     free(pReverse);
16     return pstr;
17 }
18 @end

 

  主函数测试:

 1 //  main.m
 2 //  字符串的反转
 3 //
 4 //  Created by ma c on 15/8/18.
 5 //  Copyright (c) 2015年. All rights reserved.
 6 //
 7 
 8 #import <Foundation/Foundation.h>
 9 #import "NSString+Reverse.h"
10 int main(int argc, const char * argv[])
11 {
12     @autoreleasepool
13     {
14         NSMutableString *string = [NSMutableString stringWithFormat:@"XYQ-CHINA"];
15         NSString *str = [NSString stringWithString:[string Reverse]];
16         NSLog(@"%@",str);
17     }
18     return 0;
19 }

    测试结果如下:

2015-08-18 19:42:56.696 字符串的反转[2222:136571] ANIHC-QYX
Program ended with exit code: 0

 

posted @ 2015-08-18 19:43  XYQ全哥  阅读(2174)  评论(0编辑  收藏  举报